Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Implement your own Atoi function in Go (Golang)

Posted on August 18, 2021August 18, 2021 by admin

Table of Contents

  • Overview
  • Program

Overview

Atoi function converts a given string into its number representation.  For eg

Input: "121"
Output: 121

Input: "-121"
Output: 121

Input: "0"
Output: 0

Program

Below is the program for the same.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	output := myAtoi("121")
	fmt.Println(output)

	output = myAtoi("-121")
	fmt.Println(output)

	output = myAtoi("0")
	fmt.Println(output)
}

func myAtoi(s string) int {

	var output int

	sign := "positive"
	if string(s[0]) == "-" {
		sign = "negtive"
		s = s[1:]
	} else if string(s[0]) == "+" {
		s = s[1:]
	}

	stringLen := len(s)

	for i := 0; i < stringLen; i++ {
		tempNum, _ := strconv.Atoi(string(s[i]))
		output = output*10 + tempNum
	}

	if sign == "negtive" {
		output = output * -1
	}

	return output
}

Output

121
-121
0
  • go
  • golang
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme