[Leetcode]008.String to Integer (atoi)

public class Solution {
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 ++;
    }

    //4. 转变为int,并且避免溢出
    while(index < str.length()){
        int digit = str.charAt(index) - '0';
        if(digit < 0 || digit > 9) break;

        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;
}
}
posted @ 2016-05-18 11:01  zhou23  阅读(118)  评论(0编辑  收藏  举报