Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 00e41ba

Browse files
committed
7
1 parent d898cec commit 00e41ba

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

‎7. Reverse Integer.java

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/*
2+
习题:
3+
Given a 32-bit signed integer, reverse digits of an integer.
4+
5+
Example 1:
6+
7+
Input: 123
8+
Output: 321
9+
Example 2:
10+
11+
Input: -123
12+
Output: -321
13+
Example 3:
14+
15+
Input: 120
16+
Output: 21
17+
Note:
18+
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range.
19+
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
20+
21+
*/
22+
/*
23+
解析:
24+
25+
这题其实理解起来不难,题目要求逆序输出。
26+
逆序输出不难,但是难点是32bit ,一旦溢出要返回0。那怎么判断溢出?
27+
28+
因为是32位的有符号的整数,最大的十进制就是-(2^31)-1 ~ 2^31 -1
29+
30+
31+
32+
*/
33+
34+
/*
35+
分解数位
36+
37+
%:分解成个位数字
38+
/: 去除个位数字。
39+
逆序数字就是:(分解个位数字之后)*10+个位数字
40+
41+
具体代码如下:
42+
43+
*/
44+
45+
class Solution {
46+
public int reverse(int x) {
47+
int digit = 0;
48+
int result = 0;
49+
int sybol=0;//带符号,0代表负号,1代表正号。
50+
51+
//因为是x是带符号的,所以分情况讨论
52+
if(x>0) {
53+
sybol=1;
54+
}
55+
else {
56+
sybol=0;
57+
x = -x;
58+
}
59+
60+
//对于溢出的问题进行处理
61+
if(x>=2147483647) {
62+
return 0;
63+
}
64+
65+
while(x>0){
66+
digit = x % 10;
67+
//对于溢出的问题进行处理。
68+
if(result >2147483647/10.0)
69+
return 0;
70+
result = result*10+digit;
71+
x = x/10;
72+
}
73+
74+
return (sybol==1)?result:-result;
75+
}
76+
}
77+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /