题目类型:字符串
题意:
实现atoi函数(String转化成int)
- 注意各种边界情况。
我的思路:
循环遍历string的每一个字符,res += res * 10 + c;
- 如果string为空,return 0;
- 如果只有符号,非法–return 0
- 如果有多个符号,非法–return 0
- 若字符串开头有空格,不影响–==string.trim()==把字符串前后的空格去掉
- 若数字部分已经开始,后面有非法字符,那么输出目前的数字。例如” -0012a42”输出-12
- 若溢出,输出最大值,例如”2147483648”,输出2147483647—
class Solution {
public int myAtoi(String str) {
char[] c = str.trim().toCharArray();
int len = c.length;
if (len == 0 || (!Character.isDigit(c[0]) && c[0] != '-' && c[0] != '+')) {
return 0;
}
int start = 1;
int symbol = (c[0] == '-') ? -1 : 1;
int res = Character.isDigit(c[0]) ? c[0] - '0' : 0;
while (start < len) {
if (Character.isDigit(c[start])) {
if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE/10 && c[start] - '0' > Integer.MAX_VALUE % 10)) return symbol == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;//判断是否溢出的有效方法!!
res = res * 10 + c[start] - '0';
}
else return res * symbol;
start++;
}
return res * symbol;
}
}
方法二:
beat:65%
- 对字符串去掉首尾空格:String.trim()
- 去掉首尾空格后,若长度为0,那么return 0
- 如果第一位为正负号,那么设置i为1、-1,且从第二位开始遍历
- 否则从第一位开始遍历,若遇到非数字那么停止,否则 res = res * 10 + c[index]-‘0’
- 最后,若i为-1,那么res*-1
- 注意!!在遍历过程中,判断若res超出Integer范围,那么return MAX/MIN(MAX、MIN的abs不同,所以需要res*符号来判断)
class Solution {
public int myAtoi(String str) {
char[] c= str.trim().toCharArray();
int i = 0;
double res = 0;
if(c.length == 0) return 0;
if(c[0] == '+' || (c[0] == '-')){
i = c[0] == '-' ? -1 : 1;
}else if(c[0] < '0' && c[0] > '9'){
return 0;
}
for(int j = (i == 0) ? 0 : 1; j < c.length; j++){
if(c[j] >= '0' && c[j] <= '9'){
res = res * 10 + (c[j] - '0');
if(i * res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if(i * res < Integer.MIN_VALUE) return Integer.MIN_VALUE;
}
else break;
}
return (int)(res * (i == -1 ? -1 : 1));
}
}