题目:字符串转化为整数
思路:
- 去除前后空格;
- 若字符串为空,返回0;
- 判断是否有符号;
- 逐个读取字符转化为数字
- 对于越界的判断:
res * 10 + cur > Integer.MIN_VALUE
即为越界,移项后:res > ((Integer.MAX_VALUE - cur) / 10)
代码:
import java.util.*;
public class Solution {
/**
*
* @param str string字符串
* @return int整型
*/
public int atoi (String str) {
// write code here
str = str.trim();
if (str.length() == 0) {
return 0;
}
int idx = 0;
int sign = 1;
int res = 0;
if (str.charAt(idx) == '-') {
sign = -1;
idx ++;
}
if (str.charAt(idx) == '+') {
idx ++;
}
for (; idx < str.length(); idx ++) {
int cur = str.charAt(idx) - '0';
if (cur > 9 || cur < 0) {
break;
}
if (res > ((Integer.MAX_VALUE - cur) / 10)) {
return sign == 1? Integer.MAX_VALUE: Integer.MIN_VALUE;
}
else {
res = res * 10 + cur;
}
}
return sign * res;
}
}