8. String to Integer (atoi)

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.

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.

一刷:
测试:

  1. "+-2"
  2. " 123 456"
  3. " -11919730356x"
  4. "2147483647"
  5. "-2147483648"
  6. "2147483648"
  7. "-2147483649"
  8. "+2"

这题的难点在于所有的corner case, 面试时碰到要仔细和面试官多交流

  1. 判断str是否为空或者长度是否为0
  2. 处理前后的space,也可以用str = str.trim();
  3. 尝试求出符号sign
  4. 处理数字
    (1) 假如char c = str.charAt(index)是数字,则定义int num = c - '0', 接下来判断是否越界
    1). 当前 res > Integer.MAX_VALUE / 10,越界,根据sign 返回 Integer.MAX_VALUE或者 Integer.MIN_VALUE
    2). res == Integer.MAX_VALUE / 10时, 根据最后sign和最后一位数字来决定是否越界,返回Integer.MAX_VALUE或者 Integer.MIN_VALUE
    3). 不越界情况下,res = res * 10 + num
  5. 处理非数字和‘+’, ‘-’,直接跳到6.
  6. 返回结果 res * sign
public class Solution {
    public int myAtoi(String str) {
        int res = 0;
        if(str == null || str.length() == 0) return res;
        int neg = 1, digit;
        for(int i=0; i<str.length(); i++){
            str = str.trim();
            if(str.charAt(i)=='-' && i == 0)  neg = -1;
            else if(str.charAt(i)=='+' && i == 0) neg = 1;
            else if(str.charAt(i)<'0' || str.charAt(i)>'9') return neg*res;
            else{
                digit = str.charAt(i) - '0';
                int overflow = overflow(res, digit, neg);
                if(overflow>0 ) return Integer.MAX_VALUE;
                else if(overflow<0) return Integer.MIN_VALUE;
                res = res*10 + digit;
            }
        }
        return res*neg;
        
    }
    
    private int overflow(int res, int digit, int sign){
        if(sign > 0){
           if(res>Integer.MAX_VALUE/10) return 1;
           else if(res == Integer.MAX_VALUE/10 && digit > 7) return 1;
        }
        else{
            if(res>Integer.MAX_VALUE/10) return -1;
            else if(res == Integer.MAX_VALUE/10 && digit > 8) return -1;
        }
        return 0;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容