您的位置:首页 > 编程语言 > Java开发

<LeetCode(Java版)>String to Integer

2015-09-09 21:36 459 查看

题目:

        Implement atoi to convert a string to an integer.

Hint: 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.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Update (2015-02-10):

The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

spoilers alert… click to show requirements for atoi.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

解析

  其实这道题我拿过来的时候,看到LeetCode上的通过率我都不觉得不可思议,因为明明是很简单的问题啊,但当自己敲代码时,发现其实真正的问题不是不会,而是有些输入情况没有考虑周全,本题所考的其实就是特殊输入时的程序逻辑。

  需要考虑的有:

  (1)str = null,或者str 是empty string

  (2)str的空格问题,在哪个地方出现(开头,中间,结尾)

  (3)+/-符号问题

  (4)数字越界问题

  (5)异常字符出现问题

于是有了第一版代码,虽然代码较长,但逻辑比较清楚:

public int myAtoi(String str) {

if (str == null || str.length() == 0)
return 0;
double result = 0;
int fuhaoCount = 0;// 代表负号出现的次数,只取第一次出现的负号
int zhenghaoCount = 0;// 代表正号出现的次数,只取第一次出现的正号
for (int j = 0; j < str.length(); j++) {
//出现异常字符,在这里只允许0-9,-,+与空格
if (!(str.charAt(j) >= '0' && str.charAt(j) <= '9')
&& str.charAt(j) != '-' && str.charAt(j) != '+'
&&str.charAt(j) != ' '
&& j < (str.length() - 1))
return (int)result;
else if (str.charAt(j) == '-' ) {
fuhaoCount++;
} else if (str.charAt(j) == '+') {
zhenghaoCount++;
//当正号或负号出现次数多于一次,相当于出现了异常字符
} else if(fuhaoCount > 1 || zhenghaoCount > 1){
return (int)result;
//当正好与负号都出现一次,相当于出现了异常字符
}else if (fuhaoCount == 1 && zhenghaoCount == 1) {
return (int)result;
//当出现空格时,需判断是在开头还是在数字的中间部位或者尾部
}else if(str.charAt(j) == ' '){
if(j > 1){
if(str.charAt(j-1) != ' ')
return (int)result;
}
//负号出现一次,代表是负值,如果越界,返回整数值的最小值
}else if (fuhaoCount == 1 && str.charAt(j) >= '0'
&& str.charAt(j) <= '9') {
result = result * 10 - (str.charAt(j) - '0');
if(result < Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
//计算数值,如果越界,则返回整数值的最大值
}else  if(str.charAt(j) >= '0' && str.charAt(j) <= '9'){
result = result * 10 + (str.charAt(j) - '0');
if(result > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
}
}
return (int)result;
}


  其实对于这类题,不再需要追求什么效率值,或许这种题需要的就是缜密的思考,与整洁的代码,但鉴于前面都会把执行性能贴上,在这里也贴上性能,Runtime: 336 ms,Your runtime beats 78.40% of java submissions.(Leetcode上跑出来的性能不会一成不变的,又一次这个代码跑出了200多一点点毫秒,击败了100%的提交,我也是醉了)

  从上面的分类可以看出,虽然分的很细,但是有很多地方都可以简化,比如下面这个代码,这是我在discuss区看到的代码,逻辑清晰,代码简洁,运行时间基本一致,这应该就是本题要求的代码!

public int myAtoi(String str) {
if (str == null || str.length() < 1)
return 0;

// trim white spaces
str = str.trim();

char flag = '+';

// check negative or positive
int i = 0;
if (str.charAt(0) == '-') {
flag = '-';

b341
i++;
} else if (str.charAt(0) == '+') {
i++;
}
// use double to store result
double result = 0;

// calculate value
while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
result = result * 10 + (str.charAt(i) - '0');
i++;
}

if (flag == '-')
result = -result;

// handle max and min
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;

if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;

return (int) result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java String Integer