-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverse Integer
More file actions
41 lines (35 loc) · 917 Bytes
/
Copy pathReverse Integer
File metadata and controls
41 lines (35 loc) · 917 Bytes
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
#include <iostream>
#include <cmath>
using namespace std;
/*
* 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.
*/
class Solution {
public:
int reverse(int x) {
int copy = x;
int length = 0;
while(copy) {
copy /= 10;
length++;
}
int rev = 0;
length--;
while(x) {
if(rev + (x%10) * pow(10,length) > INT_MAX || rev + (x%10) * pow(10,length) < INT_MIN)
return 0;
rev += (x%10) * pow(10,length);
x /= 10;
length--;
}
return rev;
}
};
int main() {
Solution s = Solution();
cout << s.reverse(123) << endl;
cout << s.reverse(-987654) << endl;
cout << s.reverse(2147483645) << endl;
return 0;
}