NOTE

Convert a String to an Integer

Record character parsing and atoi implementations for converting a string to an integer.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Problem Description

Convert a string to an integer without using a library function that converts strings to integers. Return 0 if the value is 0 or if the string is not a valid numeric value.

2. Approach

  • Convert it to a character array, character - '0' -> digit

3. Implementation

// Time complexity: O(N)
// Space complexity: O(1)
func StrToInt(str string) int {
	if len(str) == 0 {
		return 0
	}

	chars := []rune(str)
	data := 0
	opt := 1

	for i := 0; i < len(chars); i++ {
		ch := chars[i]
		if ch >= '0' && ch <= '9' {
			r := ch - '0'
			data = data*10 + int(r)
		} else if ch == '-' && i == 0 {
			opt = -1
		} else if ch == '+' && i == 0 {
			opt = 1
		} else {
			return 0
		}

	}
	return opt * data
}
func myAtoi(s string) int {
    i := 0
    n := len(s)
    for i < n && s[i] == ' '{
        i++
    }

    opt := 1
    if i < n {
        if s[i] == '+' {
            opt = 1
            i++
        }else if s[i] == '-' {
            opt = -1
            i++
        }
    }

    res := 0
    for i < n && s[i] >= '0' && s[i] <= '9' {
        res = res * 10 +int(s[i]-'0')
        if opt*res < math.MinInt32 {
            return math.MinInt32
        }else if opt*res > math.MaxInt32 {
            return math.MaxInt32
        }
        i++
    }
    return opt*res

}

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub