[Leetcode] String to Integer (atoi) 字符串转整数

String to Integer (atoi)

Implement atoi to convert a string to an integer.java

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.ide

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.ui

通用方法

复杂度

时间 O(n) 空间 O(1)this

思路

字符串题通常考查的都是边界条件、特殊状况的处理。因此遇到此题必定要问清楚各类条件下的输入输出应该是什么样的。这里已知的特殊状况有:code

  • 可以排除首部的空格,从第一个非空字符开始计算
  • 容许数字以正负号(+-)开头
  • 遇到非法字符便中止转换,返回当前已经转换的值,若是开头就是非法字符则返回0
  • 在转换结果溢出时返回特定值,这里是最大/最小整数

注意

  • 检查溢出时最大整数要先减去即将加的最末位再除以10,来处理"2147483648"相似的状况
  • 能够参考glibc中stdlib/atoi.c的实现方法

代码

javapublic class Solution {
    public int myAtoi(String str) {
        str = str.trim();
        int result = 0;
        boolean isPos = true;
        for(int i = 0; i < str.length(); i++){
            char c = str.charAt(i);
            if(i==0 && (c=='-'||c=='+')){
                isPos = c=='+'?true:false;
            } else if (c>='0' && c<='9'){
                // 检查溢出状况
                if(result>(Integer.MAX_VALUE - (c - '0'))/10){
                    return isPos? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
                result *= 10;
                result += c - '0';
            } else {
                return isPos?result:-result;
            }
        }
        return isPos?result:-result;
    }
}
相关文章
相关标签/搜索