题目描述:
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。
数值为0或者字符串不是一个合法的数值则返回0。
输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0
示例:
输入
+2147483647
1a33
输出
2147483647
0
思路:
1)一个一个与‘0’-‘9’判断,一旦不符合就返回0 2)注意第一个判断和int数值溢出判断
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
int res = s.StrToInt("123");
System.out.println(res);
}
public int StrToInt(String str) {
if (str == null || str.trim().length() == 0)
return 0;
char first = str.charAt(0);
//第一个非法直接返回0
if (!(first == '+' || first == '-' || (first >= '0' && first <= '9'))) {
return 0;
}
long res = 0;
int s = 1;//记录是否为负数,最后相乘
if (first == '-') {
s = -1;
}
for (int i = (first == '+' || first == '-') ? 1 : 0; i < str.length(); i++) {
if (!(str.charAt(i) >= '0' && str.charAt(i) <= '9')) {
return 0;
}
res = (res << 1) + (res << 3) + (str.charAt(i) & 0xf);
// 和 res = res * 10 + (str.charAt(i) - '0');是一样的。左移1位是乘以2的次方。
// (res << 1) + (res << 3) = res * 2 + res * 8 = res * 10 。
// 字符'0'到'9'的ascii值的低4个二进制位刚好就是0到9所以str[i]&0xf等于str[i]-'0'。
// 位运算会比乘法运算效率高那么一点点点点...
}
//!!!重要:防止溢出int的范围,否则不通过
res *= s;
if (res >= Integer.MIN_VALUE && res <= Integer.MAX_VALUE)
return (int) res;
return 0;
}
}