-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path007_Reverse_Integer.cpp
44 lines (44 loc) · 1017 Bytes
/
007_Reverse_Integer.cpp
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
#include<string>
#include<cstdlib>
#include<climits>
#include<iostream>
#include<algorithm>
using namespace std;
class Solution
{
public:
int reverse2(int x)
{
long long t = 0;
for( ; x ; x /= 10){
t = t * 10 + x % 10;
if (t > INT_MAX || t < INT_MIN) return 0;
}
return t;
}
int reverse(int x)
{
int negative = 1;
int64_t xx = x;
if( xx < 0)
{
negative = -1;
xx = -1*xx;
}
string x_s = to_string(xx);
std::reverse(x_s.begin(), x_s.end());
string int_max = to_string(INT32_MAX);
if(x_s.length() == int_max.length() and x_s > int_max)
return 0;
return negative * stoi(x_s);;
}
};
int main(int argc, char const *argv[])
{
Solution s;
cout<<"range " << INT32_MIN << "\t"<< INT32_MAX<<endl;
cout<<s.reverse(-2147483648)<<endl;
cout<<s.reverse(123)<<endl;
cout<<s.reverse(1534236469)<<endl;
return 0;
}