8. String to Integer (atoi) [Medium]

/**
 * 自己的代码,没找到很好的思路,起码通过了
 * Runtime: 3 ms, faster than 24.76%
 * Memory Usage: 38.8 MB, less than 69.53%
 */
class Solution {
    public int myAtoi(String s) {
        StringBuffer sb = new StringBuffer();
        int length = s.length(), idx = 0;
        char first;
        try {
            while (s.charAt(idx) == ' ') // 去掉字符串开头的所有空格,如果idx超出范围了就catch exception,return 0
                idx++;
            first = s.charAt(idx); // 获得空格后的第一个字符,如果idx超出范围了就catch exception,return 0
        } catch (Exception e) {
            return 0;
        }
        if (first != '+' && first != '-' && (first > '9' || first < '0')) // 空格后的第一个字符既不是正负号也不是数字,return 0
            return 0;
        sb.append(first);
        while (++idx < length && s.charAt(idx) <= '9' && s.charAt(idx) >= '0') // 循环直到数字部分结束
            sb.append(s.charAt(idx++));
        try {
            return Integer.parseInt(sb.toString()); 
        } catch (Exception e) {
            if (sb.length() == 1) // 只有符号位
                return 0;
            if (sb.charAt(0) == '-') // 负数溢出
                return Integer.MIN_VALUE;
            return Integer.MAX_VALUE; // 正数溢出
        }
    }
}
/**
 * 题目可能不让用Integer.parseInt()方法
 * 注意下面用的判断加入新数字是否会溢出的方法、trim()方法、Character.isDigit()方法
 * Runtime: 2 ms, faster than 54.18%
 * Memory Usage: 39.1 MB, less than 41.09%
 */
class Solution {
    public int myAtoi(String s) {
        s = s.trim(); // 去除s首尾的空格
        if (s.length() == 0)
            return 0;
        int idx = 1, flag = 1, res = 0; // flag记录正负号
        
        char first = s.charAt(0); // 单独处理第一个字符
        if (first == '-') 
            flag = -1;
        else if (Character.isDigit(first))
            res += first - '0';
        else if (first != '+') // 既不是正负号也不是数字
            return 0;
        
        while (idx < s.length() && Character.isDigit(s.charAt(idx))) { // 循环构造将字符串转换为数字,直到出现了非数字字符
            if (res > (Integer.MAX_VALUE - s.charAt(idx) + '0') / 10) // 加入当前字符对应数字,超出int上界
                return flag == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            res = res * 10 + s.charAt(idx++) - '0';
        }
        
        return flag * res;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值