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;
}
}

相关文章:

  • 2021-09-14
  • 2021-05-21
  • 2021-06-07
  • 2021-09-17
  • 2022-12-23
  • 2022-12-23
  • 2021-11-17
猜你喜欢
  • 2022-02-05
  • 2022-01-20
  • 2021-10-27
  • 2021-12-08
  • 2022-01-12
相关资源
相似解决方案