Skip to content

Latest commit

 

History

History
90 lines (72 loc) · 2.99 KB

8 String to Integer (atoi).md

File metadata and controls

90 lines (72 loc) · 2.99 KB

8. String to Integer (atoi)

Problem

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Update (2015-02-10): The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

spoilers alert... click to show requirements for atoi.

Requirements for atoi: The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

tag:

  • math
  • string

Solution

java

从左到右遍历字符串:

  1. 跳过空白字符
  2. 正负号判断

如果出现'+'或不出现,为正 如果出现'-'为负

  1. 溢出判断

32位整数最值2147483647,-2147483648, 如果转换过程中出现21474836x, x>4且下一位为数字或x<=4且下一位>=8则溢出,根据符号返回max value 或 min value

    private static final int MAXDIV10 = Integer.MAX_VALUE/10;
    public int myAtoi(String str) {
        int i=0, n = str.length();
        while(i<n && str.charAt(i)==' ') i++;
        int sign = 1;
        if(i<n && str.charAt(i)=='+')  i++;
        else if(i<n && str.charAt(i)=='-') {sign=-1; i++;}
        int num = 0;
        while(i<n && Character.isDigit(str.charAt(i))) {
            int digit = str.charAt(i)-'0';
            if(num>MAXDIV10 || num==MAXDIV10 && digit>=8) return sign==1? Integer.MAX_VALUE : Integer.MIN_VALUE;
            num = num*10+digit;
            i++;
        }
        return sign * num;
    }

go

func atoi(s string) int {
	i, n := 0, len(s)
	for i < n && s[i] == ' ' {
		i++
	}
	sign := 1
	if i < n && s[i] == '+' {
		i++
	} else if i < n && s[i] == '-' {
		sign = -1
		i++
	}
	num := 0
	for i < n && s[i] >= '0' && s[i] <= '9' {
		digit := s[i] - '0'
		if num > MAXINT32DIV10 || num == MAXINT32DIV10 && digit >= 8 {
			if sign == 1 {
				return math.MaxInt32
			}
			return math.MinInt32
		}
		num = num*10 + digit
		i++
	}
	return sign * num
}