leetcode 8. String to Integer (atoi)

  也许是我没有理解清楚题意,为什么输入+-2的时候要输出0,而不是输出2呢。

public class Solution {
    public int myAtoi(String str) {
        
        if(str == null || str.length() < 1) return 0;
        
        boolean flag = false;
        String res = "";
        
        
        int i = 0;
        while(str.charAt(i) == ' '&& i < str.length())
            i++;

            
        if(str.charAt(i) == '-')
        {
            flag = true;
            i++;
        }
        
        else if(str.charAt(i) == '+')
            i++;
        
        
        int num = 0;
        while(i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9')
        {
            
            if(Integer.MAX_VALUE/10 < num || (Integer.MAX_VALUE/10 == num && Integer.MAX_VALUE%10 <(str.charAt(i)-'0')))//比较当前num的值,如果当前num的值等于
//Integer.MAX_VALUE/10,则判断即将添加的一位和最大值的最后一位比较,如果大于,则输出最大值最小值即可
return flag == true ? Integer.MIN_VALUE : Integer.MAX_VALUE; num = num*10+(str.charAt(i) -'0'); i++; } if(flag) return -num; else return num; } }
原文地址:https://www.cnblogs.com/zyqBlog/p/5943778.html