Skip to content

Commit 01a274c

Browse files
committed
剑指Offer,把字符串转成整数
1 parent 925fd42 commit 01a274c

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

swordoffer/StringToInt.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* 剑指Offer,把字符串转成整数
3+
*/
4+
5+
public class StringToInt {
6+
7+
public static void main(String[] args) {
8+
System.out.println(StrToInt("-2147483649"));
9+
}
10+
11+
public static int StrToInt(String str) {
12+
if (str == null || str.length() == 0) {
13+
return 0;
14+
}
15+
if (str.charAt(0) != '+' && str.charAt(0) != '-' && !(str.charAt(0) >= '0' && str.charAt(0) <= '9')) {
16+
return 0;
17+
}
18+
for (int i = 1; i < str.length(); i++) {
19+
if (! (str.charAt(i) >= '0' && str.charAt(i) <= '9') ) {
20+
return 0;
21+
}
22+
}
23+
int sum = 0;
24+
int base = 1;
25+
for (int i = str.length() - 1; i > 0; i--) {
26+
sum += (str.charAt(i) - '0' ) * base;
27+
base *= 10;
28+
}
29+
if (str.charAt(0) == '+') {
30+
if (sum < 0) {
31+
sum = 0;
32+
}
33+
}else if(str.charAt(0) == '-') {
34+
sum = 0-sum;
35+
if (sum > 0) {
36+
sum = 0;
37+
}
38+
}else{
39+
sum += (str.charAt(0) - '0' ) * base;
40+
if (sum < 0) {
41+
sum = 0;
42+
}
43+
}
44+
45+
return sum;
46+
}
47+
48+
}

0 commit comments

Comments
 (0)