0
点赞
收藏
分享

微信扫一扫

8. 字符串转换整数 (atoi)

践行数据分析 2022-01-06 阅读 39
leetcode

书森

class Solution {
    public int myAtoi(String s) {
        // 字符串为空,直接返回0
        if(s == null) return 0;
        // 取出字符串头尾空白字符
        s = s.trim();
        // 若整个字符串全是空白字符串: "    ",直接返回0
        if(s.isEmpty()) return 0;
        // 定义字符串的下标
        int idx = 0;
        // 定义符号标记
        int sign = 1;
        char firstChar = s.charAt(idx);
        // 处理边界值
        if(firstChar == '+'){
            idx++;
        }
        else if(firstChar == '-'){
            sign = -1;
            idx++;
        // 第一个字符不是数字    
        }else if(!Character.isDigit(firstChar)){
            return 0;
        }
        // 每个字符的临时放的值
        long num = 0;
        // 结果值
        long res = num * sign;
        // 遍历字符串,超出字符串长度和碰到数字退出循环
        while(idx < s.length() && Character.isDigit(s.charAt(idx))){
            num = num * 10 + Integer.parseInt(String.valueOf(s.charAt(idx)));
            res = num * sign;
            // 超出32位边界值处理
            if(res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            if(res < Integer.MIN_VALUE) return Integer.MIN_VALUE;
            idx++; 
        }
        return (int) res;
    }
}
举报

相关推荐

0 条评论