8. String to Integer (atoi)

LeetCode Link

将 string 转化为 int。规则如下:

  1. string 中允许 leading space
  2. 可以存在正负号
  3. string 中前一部分是可以转化为 int 的表达,后一部分可以是任意 characters, ignore and this is valid
  4. if invalid string, return 0
  5. if string value is greater than Integer.MAX or less than Integer.MIN,return Integer.MAX / Integer.MIN
public int myAtoi(String str) {
    if (str == null || str.length() == 0) {
        return 0;
    }
    int len = str.length();
    int index = 0;
    while (index < len && str.charAt(index) == ' ') {
        index++;
    }
    int sign = 1;
    if (index < len && (str.charAt(index) == '-' || str.charAt(index) == '+')) {
        sign = (str.charAt(index++) == '-') ? -1 : 1;
    }
    
    // invalid case
    if (index == len || str.charAt(index) > '9' || str.charAt(index) < '0') {
        return 0;
    }
    
    int res = 0;
    int maxValue = Integer.MAX_VALUE / 10;
    int lastDigitMax = (sign < 0) ? 8 : 7;
    while (index < len && str.charAt(index) >= '0' && str.charAt(index) <= '9') {
        int digit = (int)(str.charAt(index) - '0');            
        if ((res > maxValue) || (res == maxValue && digit > lastDigitMax)) {
            return (sign > 0) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        } 
        res = res * 10 + digit;
        index++;
    }
    
    return (sign < 0) ? -res : res;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容