Skip to content

Commit 96a7446

Browse files
committed
#7 反转整数,通过取余的方式分解反转字符顺序。还需要注意溢出场景处理
1 parent 22e8f9e commit 96a7446

File tree

3 files changed

+43
-9
lines changed

3 files changed

+43
-9
lines changed
+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package math;
2+
3+
/**
4+
5+
* @since 2020/3/8 10:37 PM
6+
*/
7+
public class LC_7_ReverseInteger {
8+
/**
9+
* 思路:利用 取余数的方式取最后一个个位,取出的个位参与结果组装
10+
*/
11+
public int reverse(int x) {
12+
int rev = 0;
13+
while (x != 0) {
14+
int pop = x % 10;
15+
x = x / 10;
16+
if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
17+
if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
18+
rev = rev * 10 + pop;
19+
}
20+
return rev;
21+
}
22+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package math;
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+
10+
* @since 2020/3/8 10:36 PM
11+
*/
12+
public class LC_7_ReverseIntegerTest {
13+
@Test
14+
public void reverse_integer_test() {
15+
LC_7_ReverseInteger ri = new LC_7_ReverseInteger();
16+
assertThat(ri.reverse(123), is(321));
17+
}
18+
}

pom.xml

+3-9
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,6 @@
1111
<name>RicoNut</name>
1212
<description>RicoNut</description>
1313

14-
<parent>
15-
<groupId>org.springframework.boot</groupId>
16-
<artifactId>spring-boot-starter-parent</artifactId>
17-
<version>2.0.4.RELEASE</version>
18-
<relativePath/> <!-- lookup parent from repository -->
19-
</parent>
2014

2115
<properties>
2216
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@@ -25,10 +19,10 @@
2519
</properties>
2620

2721
<dependencies>
28-
2922
<dependency>
30-
<groupId>org.springframework.boot</groupId>
31-
<artifactId>spring-boot-starter-test</artifactId>
23+
<groupId>junit</groupId>
24+
<artifactId>junit</artifactId>
25+
<version>4.12</version>
3226
<scope>test</scope>
3327
</dependency>
3428
</dependencies>

0 commit comments

Comments
 (0)