We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
2 parents 44c0c6a + ff747fe commit 564c00bCopy full SHA for 564c00b
C++/chapImplement.tex
@@ -33,15 +33,26 @@ \subsubsection{代码}
33
\begin{Code}
34
//LeetCode, Reverse Integer
35
// 时间复杂度O(logn),空间复杂度O(1)
36
+// 考虑 1.负数的情况 2. 溢出的情况(正溢出&&负溢出,比如 x = -2147483648(即-2^31) )
37
class Solution {
38
public:
39
int reverse (int x) {
- int r = 0;
40
-
41
- for (; x; x /= 10)
42
- r = r * 10 + x % 10;
43
44
- return r;
+ long long r = 0;
+ long long t = x;
+ t = t > 0 ? t : -t;
+ for (; t; t /= 10)
+ 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
53
+ return r;
54
+ }
55
56
}
57
};
58
\end{Code}
0 commit comments