《剑指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;
    }
}
全部评论

相关推荐

10-30 19:23
已编辑
山东大学(威海) C++
牛至超人:其实简历是不需要事无巨细的写的,让对方知道你有这段经历就行了,最重要的是面试的时候讲细讲明白
点赞 评论 收藏
分享
11-13 14:37
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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