剑指offer-67 字符串转整数
题目:
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
思路:
分成两个部分,符号和数字
但需要注意的是:
- null
- 空字符串""
- 只有+-
- 有+-
- 非法字符
自己解答:
public class Solution {
public int StrToInt(String str) {
if(str == null || str.length() == 0) return 0;
char[] ch = str.toCharArray();
int res = Int(ch);
return res;
}
private int unsignInt(char[] ch, int start){
int res = 0;
for(int i = start; i < ch.length; i++){
if(ch[i] >= '0' && ch[i] <= '9'){
res *= 10;
res += (ch[i] - '0');
}
else{
res = 0;
break;
}
}
return res;
}
private int Int(char[] ch){
boolean isNegtive = false;
int start = 0;
if(ch[0] == '+'){
start++;
}else if(ch[0] == '-'){
start++;
isNegtive = true;
}
int res = unsignInt(ch, start);
if(isNegtive)
return -res;
else
return res;
}
}
犯的错误:
这个代码没有考虑只有正负号(在无符号函数里面虽然会直接返回0,但本身我自己没有考虑得到),没有考虑上下溢出
注意:
优化:
public class Solution {
public int StrToInt(String str) {
if(str == null || str.length() == 0) return 0;
char[] ch = str.toCharArray();
int res = Int(ch);
return res;
}
private int Int(char[] ch){
int isNegtive = 1;
int start = 0;
if(ch[0] == '+'){
start++;
}else if(ch[0] == '-'){
start++;
isNegtive = -1;
}
long res = 0;
for(int i = start; i < ch.length; i++){
if(ch[i] >= '0' && ch[i] <= '9'){
res *= 10;
res += isNegtive * (ch[i] - '0');
if(res > 0x7fff_ffff || res < 0x8000_0000){
res = 0;
break;
}
}
else{
res = 0;
break;
}
}
return (int)res;
}
}