8. String to Integer (atoi)

LeetCode

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Solution {
private boolean is_num(char ch){
if((ch-'0'<=9)&&(ch-'0'>=0)) return true;
return false;
}
public int myAtoi(String str) {
// str is empty
if(str==null||str.length()==0) return 0;

// str contains only whitespace characters
String newStr=str.trim();
if(newStr.length()==0) return 0;

// not a plus or minus sign or numerical digit at the head
char ch=newStr.charAt(0);
if(ch!='-'&&ch!='+'&&!is_num(ch)) return 0;
// only plus or minus sign
if(ch=='-'&&newStr.length()==1||ch=='+'&&newStr.length()==1) return 0;

// multiple non-numberical digits except the plus and minus sign before integer numbers
int count=0;
while (count<newStr.length()&&!is_num(newStr.charAt(count))) {
count++;
}
if(count>1) return 0;

boolean sign=true;
StringBuilder sb=new StringBuilder();

if(newStr.charAt(0)=='-'){
sign=false;
for(int i=1;i<newStr.length();i++){
if(is_num(newStr.charAt(i)))
sb.append(newStr.charAt(i));
else break;
}
} else if(newStr.charAt(0)=='+'){
for(int i=1;i<newStr.length();i++){
if(is_num(newStr.charAt(i)))
sb.append(newStr.charAt(i));
else break;
}
} else {
for(int i=0;i<newStr.length();i++){
if(is_num(newStr.charAt(i)))
sb.append(newStr.charAt(i));
else break;
}
}

// e.g. "+0000" or "-0000" or "0000"
while (sb.charAt(0)=='0') {
sb.deleteCharAt(0);
if(sb.length()==0) return 0;
}

// if the number is too big, like bigger than maximum long integer.
if(sign&&sb.length()>10) return Integer.MAX_VALUE;
if(!sign&&sb.length()>10) return Integer.MIN_VALUE;

// to check whether integer is within the 32-bit signed integer range: [−2^31, 2^31 − 1]
if(!sign) return (0-Long.valueOf(sb.toString()))<=Integer.MIN_VALUE ?Integer.MIN_VALUE:0-Integer.valueOf(sb.toString());
return Long.valueOf(sb.toString())>=Integer.MAX_VALUE?Integer.MAX_VALUE:Integer.valueOf(sb.toString());
}
}
0%