首页 > 其他 > 详细

08.字符串转换位整数

时间:2019-09-01 16:41:24      阅读:67      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

 

 技术分享图片

 

 提交:

class Solution {
    public int myAtoi(String str) {
         str = str.trim();
        if (str == null || str.length() == 0) return 0;

        // + - 号
        char firstChar = str.charAt(0);
        int sign = 1;
        int start = 0;
        long res = 0;
        if (firstChar == ‘+‘) {
            sign = 1;
            start++;
        } else if (firstChar == ‘-‘) {
            sign = -1;
            start++;
        }

        for (int i = start; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return (int) res * sign;
            }
            res = res * 10 + str.charAt(i) - ‘0‘;
            if (sign == 1 && res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            if (sign == -1 && res > Integer.MAX_VALUE) return Integer.MIN_VALUE;
        }
        return (int) res * sign;
    }
}

评论:奇葩输入太多,只能参考别人的代码

08.字符串转换位整数

原文:https://www.cnblogs.com/baizhuang/p/11442174.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!