string to integer (atoi)


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.

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.


Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class {
public int myAtoi(String str) {
int index = 0, total = 0, sign = 1;
if(str.length() == 0) return 0;
while(str.charAt(index) == ' ' && index < str.length())
index++;
if(str.charAt(index) == '+' || str.charAt(index) == '-') {
sign = str.charAt(index)=='+'?1:-1;
index++;
}
while(index < str.length()) {
int digit = str.charAt(index) - '0';
if(digit < 0 || digit > 9) break;
if(total > Integer.MAX_VALUE/10 || (total == Integer.MAX_VALUE/10&& digit > Integer.MAX_VALUE%10)) {
return sign==1?Integer.MAX_VALUE:Integer.MIN_VALUE;
}
total = total * 10 + digit;
index++;
}
System.out.println(total);
return total*sign;
}
}