Skip to content

Commit a6f9f5a

Browse files
draft for atoi
1 parent 610e36f commit a6f9f5a

File tree

1 file changed

+57
-1
lines changed

1 file changed

+57
-1
lines changed

EASY/src/easy/StringToInteger.java

+57-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
package easy;
2+
3+
import java.util.HashSet;
24
/**8. String to Integer (atoi) QuestionEditorial Solution My Submissions
35
Total Accepted: 115114
46
Total Submissions: 839893
@@ -8,6 +10,7 @@
810
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
911
1012
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.*/
13+
import java.util.Set;
1114

1215
/**Requirements for atoi:
1316
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
@@ -28,6 +31,59 @@ public int myAtoi(String str) {
2831
//case 4: there're many leading whitespace characters which we'll have to ignore
2932

3033
//case 5: when finding the first non-whitespace character, it could possibly be a '+' or '-' sign, after that, we parse all the consecutive numbers
31-
return 0;
34+
35+
str = str.trim();//cut off its leading and trailing whitespace characters
36+
if(str == null || str.isEmpty()) return 0;
37+
Set<Character> numbers = new HashSet();
38+
for(int i = 0; i < 10; i++){
39+
numbers.add(Character.forDigit(i, 10));
40+
}
41+
42+
char[] chars = str.toCharArray();
43+
StringBuilder sb = new StringBuilder();
44+
boolean negative;
45+
int i = 0;
46+
if(chars[0] == '-') {
47+
negative = true;
48+
i++;//let i start from 1 in this case
49+
}
50+
else negative = false;
51+
52+
//it might be a floating number, so consider '.'
53+
int period = 0;
54+
while(i < chars.length && numbers.contains(chars[i])){
55+
if(chars[i] == '.') period++;
56+
if(period > 1) break;
57+
sb.append(chars[i++]);
58+
}
59+
60+
int result = 0;
61+
if(period > 0){
62+
//use Double to parse
63+
try{
64+
result = (int) Double.parseDouble(sb.toString());
65+
} catch(Exception e){
66+
System.out.println(e);
67+
}
68+
} else {
69+
//use Integer to parse
70+
try{
71+
result = Integer.parseInt(sb.toString());
72+
} catch(Exception e){
73+
System.out.println(e);
74+
}
75+
}
76+
77+
return result;
78+
}
79+
80+
public static void main(String...strings){
81+
StringToInteger test = new StringToInteger();
82+
String str = "1";
83+
System.out.println(test.myAtoi(str));
84+
85+
86+
// System.out.println(Double.parseDouble("1.2098"));
87+
// System.out.println(Integer.parseInt("123456789"));
3288
}
3389
}

0 commit comments

Comments
 (0)