String to Integer (atoi) (8 Easy)

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.

解题思路

字符串题一般考查的都是边界条件、特殊情况的处理。所以遇到此题一定要问清楚各种条件下的输入输出应该是什么样的。这里已知的特殊情况有:

  1. 能够排除首部的空格,从第一个非空字符开始计算
  2. 允许数字以正负号(+-)开头
  3. 遇到非法字符便停止转换,返回当前已经转换的值,如果开头就是非法字符则返回0
  4. 在转换结果溢出时返回特定值,这里是最大/最小整数
 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;
}

results matching ""

    No results matching ""