-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7.reverse-integer.cpp
More file actions
63 lines (63 loc) · 1.2 KB
/
7.reverse-integer.cpp
File metadata and controls
63 lines (63 loc) · 1.2 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
* @lc app=leetcode id=7 lang=cpp
*
* [7] Reverse Integer
*/
// @lc code=start
class Solution
{
public:
int MAX = 2147483647;
int D10 = 2147483647 / 10;
int reverse(int x)
{
if (x == -2147483648)
{
return 0;
}
int neg_flag = x < 0;
x = abs(x);
int num = 0;
while (1)
{
if (x == 0)
{
break;
}
int n = x % 10;
x /= 10;
if (neg_flag)
{
if (num > D10)
{
return 0;
}
num = num * 10;
if ((MAX - num) < n - 1)
{
return 0;
}
num += n;
}
else
{
if (num > D10)
{
return 0;
}
num = num * 10;
if (MAX - num < n)
{
return 0;
}
num += n;
}
}
if (neg_flag)
{
return -num;
}
return num;
}
};
// @lc code=end