您的位置:首页 > 其它

LeetCode 8 String to Integer (atoi)

2017-10-19 15:38 525 查看
原题:(频率5)

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 (20
4000
15-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.

题意:把字符串转化为数字,C++中的atoi函数

代码和思路

//把字符串转换为数字,1:去掉空格,判断格式是否正确 2:判断是否越界,我们知道整型数据的范围是INT_MIN(-2147482648)到INT_MAX(2147483647)
class Solution {
public static int myAtoi(String str) {

if (str == null || str.length() == 0){
return 0;
}
int sign = 1;
int start =0;
long sum = 0;
//去掉空格
str = str.trim();
//正还是负
char first = str.charAt(0);
if(first=='+'){
sign = 1;
start++;
}
else if(first == '-'){
sign = -1;
start++;
}

for (int i = start; i < str.length(); i++) {
//如果不是数字
if (!Character.isDigit(str.charAt(i))){
return (int) sum * sign;
}
sum = sum * 10 + str.charAt(i) - '0';
//判断是否越界
if (sign == 1 && sum > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (sign == -1 && (-1) * sum < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
}

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