Skip to content

Commit 1cdf801

Browse files
1 parent a143ff7 commit 1cdf801

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

ReverseInteger.cpp

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Solution {
2+
public:
3+
int reverse(int x) {
4+
if(x<=INT_MIN || x>INT_MAX || !x)
5+
return 0;
6+
if (x>-10 && x<10)
7+
return x;
8+
int max = 0x7FFFFFFF;
9+
int msb = 0x80000000;
10+
int toggle = 0xFFFFFFFF;
11+
int answer = 0;
12+
bool s = true;
13+
if(x<0) {
14+
// Reversing the two's compliment
15+
x -= 1;
16+
x ^= toggle;
17+
s = false;
18+
}
19+
int i=1;
20+
while(x>0) {
21+
//cout<<"\n "<<i++<<"\t"<<static_cast<long int>(answer)*10;
22+
if (static_cast<long int>(answer)*10 + x%10 > max) {
23+
return 0;
24+
}
25+
answer *= 10;
26+
answer += x%10;
27+
x /= 10;
28+
}
29+
if (!s)
30+
return -answer;
31+
return answer;
32+
}
33+
};
34+
35+
int stringToInteger(string input) {
36+
return stoi(input);
37+
}
38+
39+
int main() {
40+
string line;
41+
while (getline(cin, line)) {
42+
int x = stringToInteger(line);
43+
44+
int ret = Solution().reverse(x);
45+
46+
string out = to_string(ret);
47+
cout << out << endl;
48+
}
49+
return 0;
50+
}

0 commit comments

Comments
 (0)