Skip to content

Commit 35fb28b

Browse files
Reverse Integer Problem
1 parent 8bfd623 commit 35fb28b

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
Reverse Integer
3+
4+
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.
5+
6+
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
7+
8+
9+
Example 1:
10+
11+
Input: x = 123
12+
Output: 321
13+
Example 2:
14+
15+
Input: x = -123
16+
Output: -321
17+
Example 3:
18+
19+
Input: x = 120
20+
Output: 21
21+
Example 4:
22+
23+
Input: x = 0
24+
Output: 0
25+
26+
27+
Constraints:
28+
29+
-2^31 <= x <= 2^31 - 1
30+
*/
31+
32+
// Solution
33+
34+
class Solution {
35+
public:
36+
int reverse(int x) {
37+
38+
long long resultant = 0;
39+
40+
while(x) {
41+
resultant = resultant * 10 + x % 10;
42+
x /= 10;
43+
}
44+
45+
return (resultant <= INT32_MIN || resultant >= INT32_MAX) ? 0 : resultant;
46+
47+
}
48+
};

0 commit comments

Comments
 (0)