Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 81267c5

Browse files
committed
#8 字符串转换成整数
1 parent 2b629ca commit 81267c5

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package array;
2+
3+
/**
4+
* @author liangqian0723@gmail.com
5+
* @since 2020/4/3 6:58 AM
6+
*/
7+
public class LC_8_StringToIntegerAtoi {
8+
public int myAtoi(String str) {
9+
if (null == str || str.length() == 0) return 0;
10+
char[] array = str.toCharArray();
11+
int res = 0;
12+
int curIndex = 0;
13+
int flag = 1;
14+
while (array[curIndex] == ' ') {
15+
curIndex++;
16+
if (curIndex >= str.length()) return 0;
17+
}
18+
if (array[curIndex] == '-') flag = -1;
19+
if (array[curIndex] == '+' || array[curIndex] == '-') curIndex++;
20+
while (curIndex < str.length() && Character.isDigit(array[curIndex])) {
21+
int r = array[curIndex] - '0';
22+
if (res > (Integer.MAX_VALUE - r) / 10 || res < Integer.MIN_VALUE / 10) {
23+
return flag > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
24+
}
25+
res = res * 10 + r;
26+
curIndex++;
27+
}
28+
return flag > 0 ? res : res * flag;
29+
}
30+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package array;
2+
3+
import org.junit.Test;
4+
5+
import static org.hamcrest.core.Is.is;
6+
import static org.junit.Assert.assertThat;
7+
8+
/**
9+
* @author liangqian0723@gmail.com
10+
* @since 2020/4/3 6:56 AM
11+
*/
12+
public class LC_8_StringToIntegerAtoiTest {
13+
@Test
14+
public void test_string_to_integer_atomic() {
15+
LC_8_StringToIntegerAtoi at = new LC_8_StringToIntegerAtoi();
16+
assertThat(at.myAtoi(" -42"), is(-42));
17+
assertThat(at.myAtoi("4193 with words"), is(4193));
18+
assertThat(at.myAtoi("words and 987"), is(0));
19+
assertThat(at.myAtoi(" "), is(0));
20+
assertThat(at.myAtoi("2147483648"), is(2147483647));
21+
}
22+
}

0 commit comments

Comments
 (0)