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

Leetcode-8. String to Integer (atoi)

2016-09-28 17:51 260 查看
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————
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.

这个题目感觉没什么意义啊,还说是提示。。不提示我怎么知道你输入是什么鬼,而且不同的输入我应该返回什么值。Your runtime beats 46.06% of java submissions.

public class Solution {
public int myAtoi(String str) {
if(str.length() == 0) return 0;
int negative = 1;
long result = 0;
int i = 0;
for(;i < str.length(); i++){
if(str.charAt(i) == '-'){
negative = -1;
i++;
break;
}else if(str.charAt(i) == '+'){
negative = 1;
i++;
break;
}else if(str.charAt(i) - '0' >= 0 && str.charAt(i) - '0' <= 9){
break;
}else if(str.charAt(i) != ' '){
return 0;
}
}
for(;i < str.length(); i++){
if(str.charAt(i) - '0' >= 0 && str.charAt(i) - '0' <= 9){
result *= 10;
result += (str.charAt(i) - '0')*negative;
}else{
break;
}

if(result > 2147483647){ result = 2147483647;break;}
else if( result < -2147483648) {result = -2147483648;break;}
}

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