标签:
Implement atoi to convert a string to an integer.
Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
题目:实现字符串转整数
注意事项:考虑好各种可能的输入(坑);
public class Solution {
public int myAtoi(String str) {
}
}
解题感受:题目本身不是特别难,只要找到一个基准,java中是‘0‘(char)依据输入字符串中的每个字符,与基准之间的差值,确定进制进行相乘累加,判断+,-,思路非常简单,难点在于:
1.各种极端的边界参数,leetcode的test上有1047个case,估计大部分失败都是在" -+12","-","+"," 12a34"之类的corner cases上;
2.int整数上下边界的处理;
对于边界,我这里直接用了double进行扩大而后转为int,暂时想不出啊好的处理方法,代码以下:
public int myAtoi(String str) {
if (str == null || str.length() == 0) {
return 0;
}
boolean flag_neg = false;
str = str.trim();
int len = str.length() - 1;
double digit = 1, count = 0,res = 0;
char std = ‘0‘;
while (len >= 0) {
char c = str.charAt(len);
if (‘-‘ == c) {
flag_neg = true;
count++;
} else if (c == ‘+‘) {
flag_neg = false;
count++;
} else if (c >= ‘0‘ && c <= ‘9‘) {
int con = str.charAt(len) - std;
res += con * digit;
digit *= 10;
} else {
res = 0;
digit = 1;
}
len--;
}
res = flag_neg ? -res : res;
if (res >= Integer.MAX_VALUE) {
res = Integer.MAX_VALUE;
} else if (res <= Integer.MIN_VALUE) {
res = Integer.MIN_VALUE;
}
if (count > 1)return 0;
return (int) res;
}
leetcode - String to Integer (atoi) 字符串转整数
标签:
原文地址:http://www.cnblogs.com/wujunjie/p/5650974.html