Skip to content

Commit 775c9b4

Browse files
committed
feat: solved 8
1 parent 709bccc commit 775c9b4

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package com.fghpdf.StringToInteger;
2+
3+
/**
4+
* @author fghpdf
5+
* @date 2019/11/10
6+
* https://leetcode.com/problems/string-to-integer-atoi/
7+
*
8+
* if else practice
9+
**/
10+
public class Solution {
11+
public int myAtoi(String str) {
12+
str = str.trim();
13+
if (str.length() == 0) {
14+
return 0;
15+
}
16+
if (!isValid(str)) {
17+
return 0;
18+
}
19+
20+
int start = 0;
21+
char sign = str.charAt(0);
22+
if (sign == '+' || sign == '-') {
23+
start = 1;
24+
}
25+
26+
for (int i = start; i < str.length(); i++) {
27+
char c = str.charAt(i);
28+
if (!Character.isDigit(c)) {
29+
str = str.substring(0, i);
30+
break;
31+
}
32+
}
33+
34+
try {
35+
return Integer.parseInt(str);
36+
} catch (NumberFormatException error) {
37+
if (sign == '+' || Character.isDigit(sign)) {
38+
return 2147483647;
39+
}
40+
41+
if (sign == '-') {
42+
return -2147483648;
43+
}
44+
}
45+
46+
return 0;
47+
}
48+
49+
private boolean isValid(String str) {
50+
char c1 = str.charAt(0);
51+
52+
if (Character.isLetter(c1)) {
53+
return false;
54+
}
55+
56+
if (Character.isDigit(c1)) {
57+
return true;
58+
}
59+
60+
if ('+' == c1 || '-' == c1) {
61+
if (str.length() < 2) {
62+
return false;
63+
}
64+
char c2 = str.charAt(1);
65+
return Character.isDigit(c2);
66+
}
67+
68+
return false;
69+
}
70+
71+
public static void main(String[] args) {
72+
Solution sol = new Solution();
73+
System.out.println(sol.myAtoi("20000000000000000000"));
74+
}
75+
}

0 commit comments

Comments
 (0)