《剑指Offer》67. 把字符串转换成整数

题目链接

牛客网

题目描述

将一个字符串转换成一个整数,字符串不是一个合法的数值则返回 0,要求不能使用字符串转换整数的库函数。

Iuput:
+2147483647
1a33

Output:
2147483647
0

解题思路

public class Solution {
   
    public int StrToInt(String str) {
   
        if (str==null || str.length()==0) return 0;
        boolean isNegative = str.charAt(0)=='-';
        long res = 0;
        for (int i=0;i<str.length();i++) {
   
            char c = str.charAt(i);
            if (i==0 && (c=='+' ||c=='-')) continue;
            if (c>'9' || c<'0') return 0;
            // 用来判断是否越界
            if (isNegative && res>(Integer.MAX_VALUE+1-(c-'0'))/10) return 0;
            if (!isNegative && res>(Integer.MAX_VALUE-(c-'0'))/10) return 0;
            res = res*10 + (c-'0');
        }
        return isNegative? -(int)res: (int)res;
    }
}
全部评论

相关推荐

程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务