8000 Merge pull request #63 from LiEmail/patch-1 · laisun/leetcode@564c00b · GitHub
[go: up one dir, main page]

Skip to content
Sign in

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

Appearance settings

Commit 564c00b

Browse files
committed
Merge pull request soulmachine#63 from LiEmail/patch-1
进一步完善[Reverse Integer]
2 parents 44c0c6a + ff747fe commit 564c00b

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

C++/chapImplement.tex

+17-6
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,26 @@ \subsubsection{代码}
3333
\begin{Code}
3434
//LeetCode, Reverse Integer
3535
// 时间复杂度O(logn),空间复杂度O(1)
36+
// 考虑 1.负数的情况 2. 溢出的情况(正溢出&&负溢出,比如 x = -2147483648(即-2^31) )
3637
class Solution {
3738
public:
3839
int reverse (int x) {
39-
int r = 0;
40-
41-
for (; x; x /= 10)
42-
r = r * 10 + x % 10;
43-
44-
return r;
40+
long long r = 0;
41+
long long t = x;
42+
t = t > 0 ? t : -t;
43+
for (; t; t /= 10)
44+
r = r * 10 + t % 10;
45+
46+
bool sign = x > 0 ? false: true;
47+
if (r > 2147483647 || (sign && r > 2147483648)) {
48+
return 0;
49+
} else {
50+
if (sign) {
51+
return -r;
52+
} else {
53+
return r;
54+
}
55+
}
4556
}
4657
};
4758
\end{Code}

0 commit comments

Comments
 (0)
0