【leetcode】8. String to Integer (atoi)

来源:互联网 发布:php注册登陆页面代码 编辑:程序博客网 时间:2024/06/07 22:59

问题描述:

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.

思路:

看似很简单的一道题,但是通过率很低(13.8)。原因是很难把所以情况都一次性考虑到。这道题能反应一个程序员的经验和缜密的逻辑。

需要考虑的输入情况有:1,空输入;2,字符串开头为“ ”;3,正负号;4,溢出。解决方案如下:

public int myAtoi(String str) {    int index = 0, sign = 1, total = 0;    //1. 空输入:    if(str.length() == 0) return 0;    //2. 以空字符开头:    while(str.charAt(index) == ' ' && index < str.length())        index ++;    //3. 正负号:    if(str.charAt(index) == '+' || str.charAt(index) == '-'){        sign = str.charAt(index) == '+' ? 1 : -1;        index ++;    }    while(index < str.length()){        int digit = str.charAt(index) - '0';        if(digit < 0 || digit > 9) break;        //4:解决溢出问题;        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 = 10 * total + digit;        index ++;    }    return total * sign;}
1 0