-
Notifications
You must be signed in to change notification settings - Fork 0
/
StringToInteger.java
75 lines (58 loc) · 1.54 KB
/
StringToInteger.java
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
66
67
68
69
70
71
72
73
74
75
package me.rainking;
/**
* @author Rain
* @date 2018/5/19
*/
public class StringToInteger {
public static void main(String[] args) {
StringToInteger o = new StringToInteger();
String[] strArr = {"42", " -42", "4193 with words",
"words and 987", "-91283472332", "", " "};
for (String str : strArr) {
System.out.println(o.myAtoi2(str));
}
}
// - 45 0 48 - 57
public int myAtoi(String str) {
str = str.trim();
int length = str.length();
if (length < 1) {
return 0;
}
boolean isPositive;
int start;
if (str.charAt(0) == '-') {
isPositive = false;
start = 1;
} else if (str.charAt(0) == '+') {
isPositive = true;
start = 1;
} else {
isPositive = true;
start = 0;
}
int sum = 0;
for (int index = start; index < length; index++) {
int intValue = str.charAt(index) - 48;
if (intValue < 0 || 9 < intValue) {
break;
} else {
sum = sum * 10 + intValue;
}
if (sum % 10 != intValue) {
if (isPositive) {
return 2147483647;
} else {
return -2147483648;
}
}
}
if (!isPositive) {
sum = -sum;
}
return sum;
}
public int myAtoi2(String str) {
return 0;
}
}