1

[Golang] Atoi for Decimal Integer

 2 years ago
source link: http://siongui.github.io/2017/04/29/go-atoi-for-decimal-integer/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introduction

I read the post of Write your own atoi() in GeeksforGeeks [1], and feel it is a good exercise to implement my own atoi in Go, that takes a string (which represents an decimal integer) as an argument and returns its value in int type.

Go standard library already provides this function, see strconv.Atoi for more information.

atoi Implementation

Run Code on Go Playground

import (
      "errors"
)

var m = map[rune]int{
      '0': 0,
      '1': 1,
      '2': 2,
      '3': 3,
      '4': 4,
      '5': 5,
      '6': 6,
      '7': 7,
      '8': 8,
      '9': 9,
}

// input: string of decimal integer number
func Atoi(ds string) (di int, err error) {
      if len(ds) == 0 {
              err = errors.New("input length is zero")
              return
      }

      sign := 1
      if ds[0] == '-' {
              sign = -1
              ds = ds[1:]
              if len(ds) == 0 {
                      err = errors.New("invalid input: -")
                      return
              }
      }

      for _, digit := range ds {
              if d, ok := m[digit]; ok {
                      di = di*10 + d
              } else {
                      err = errors.New("invalid digit: " + string(digit))
                      return
              }
      }

      di = di * sign
      return
}

Tested on: Go Playground


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK