您的位置:首页 > Web前端

剑指offer50题(把字符串转换成整数)

2018-01-08 10:23 766 查看
题目:将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0

思路:把字符串的数字转换成整数,注意有无符号数的边界问题(上溢出、下溢出)即可。

代码:

public class Solution {
public int StrToInt(String str) {
if(str == null || str.length()==0)
return 0;
int start;
int tag;
if(str.charAt(0)=='+'){
start=1;
tag=1;
}
else if(str.charAt(0)=='-'){
start=1;
tag=0;
}
else{
start=0;
tag=1;
}
long result = 0;
for(int i=start;i<str.length();i++){
char temp = str.charAt(i);
if(temp>='0' && temp<='9'){
result = result*10+(temp-'0');
if(tag==1 && result>Integer.MAX_VALUE)
throw new RuntimeException("上溢出");
if(tag==0 && result<Integer.MIN_VALUE)
throw new RuntimeException("下溢出");
}
else{
return 0;
}
}
if(tag==0){
return (int)(-1*result);
}
else{
return (int)result;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: