Skip to content

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

Lines changed: 17 additions & 6 deletions
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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy