forked from lilong-dream/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseInteger.java
More file actions
44 lines (35 loc) · 936 Bytes
/
ReverseInteger.java
File metadata and controls
44 lines (35 loc) · 936 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Author: Li Long, [email protected]
// Date: Apr 17, 2014
// Source: http://oj.leetcode.com/problems/reverse-integer/
// Analysis: http://blog.csdn.net/lilong_dream/article/details/19674929
// Reverse digits of an integer.
// Example1: x = 123, return 321
// Example2: x = -123, return -321
public class ReverseInteger {
public int reverse(int x) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
int result = 0;
int flag = 0;
if (x < 0) {
flag = 1;
x = -x;
}
int lastDigit = 0;
while (x > 0) {
lastDigit = x - x / 10 * 10;
result = result * 10 + lastDigit;
x /= 10;
}
if (flag == 1) {
result = -result;
}
return result;
}
public static void main(String[] args) {
ReverseInteger slt = new ReverseInteger();
int x = 10;
int res = slt.reverse(x);
System.out.print(res);
}
}