File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments