String to Integer (atoi)

Leave a comment

November 22, 2016 by oneOokay

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.

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.


所有的input的形式按顺序分为四个阶段:

  1. 首空格
  2. + – 号 (可能出现也可能不出现)
  3. 数字
  4. 数字之后的所有其他

实现方面用一个index指针来逐步扫描我觉得比用for-loop更好:for-loop需要处理我对目前的char的期待值是什么,比较复杂。而且用指针的话就能够分段来逐个击破。每一段都有不同的期待值。

  • 对正负号的处理:用一个int sign来表示(比用boolean好):
    • 正号的话sign = 1; 负号的话sign=-1.返回值为最终的值乘以sign.(免去了一个=?logict)
  • 对是否overflow的处理:与Integer.MAX_VALUE的比较方法.
    • 在对res * 10之前,把它跟Max_Value / 10 以及 把当前digit与max_value的个位数字相比较
    • Integer.MAX_VALUE: 的个位是7
    • Integer.MIN_VALUE:的个位是8
  • 把char转换成int的方法:char – ‘0’.同时还能够排除非数字的char.
public class Solution {
    public int myAtoi(String str) {
        if (str == null || str.length() == 0){
            return 0;
        }        
        char[] chs = str.toCharArray();
        int total = 0;
        int sign = 1; 
        int index = 0;
        //第一阶段:期待值:' '; 需要去掉' '
        while(chs[index] == ' ' && index < str.length()){
            index ++;
        }
        //第二阶段:期待值:'+' 或 '-'
        if (chs[index] == '-' || chs[index] == '+'){
            sign = chs[index] == '+'? 1 : -1;
            index ++;
        }//这里不能else return,因为也可能直接出现数字(省略了+号)
        
        //第三阶段:期待纯数字
        while(index < str.length()){             
            //把char转换成int的一个很妙的方法,还能够排除非数字的char            
            int digit = chs[index] - '0'; 
            if (digit > 9 || digit < 0){
                break; //遇到了非法的数字,直接结束循环e.g. "123a"返回123
            }
//判断是否overflow的方法;注意是max value小于目前的total
//注意这里是只有当十位数字之前与max_value相同,
//个位数字为8的时候才会进入到这个if里面
//当数字为正数的时候,超过正数limit了,返回max_value
//但数字为负数的时候,并没有超过负数的limit,而是正好为min_value
//所以这里返回也是没有任何问题的
            if (Integer.MAX_VALUE / 10 < total || 
Integer.MAX_VALUE / 10 == total && Integer.MAX_VALUE % 10 < digit){
                return sign == 1? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            total = total * 10 + digit; //加入新的char继续构成数字
            index ++;
        }
        return total * sign;//加上正负号
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: