-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_integer.cpp
More file actions
65 lines (57 loc) · 1.05 KB
/
reverse_integer.cpp
File metadata and controls
65 lines (57 loc) · 1.05 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
64
65
#include <iostream>
#include <string>
#include <sstream>
#include <typeinfo>
using namespace std;
class Solution
{
public:
int reverse(int x)
{
bool isNegative = false;
if (x < 0)
{
isNegative = true;
try
{
// 2147483648 to 2147483647
if (x < -2147483647)
return 0;
x = x * -1; // convert int to positive
cout << x << '\n';
}
catch (const exception &e)
{
cout << "Error :: " << e.what();
return 0;
}
}
string s;
stringstream ss;
ss << x;
ss >> s;
string revS;
for (int i = s.length() - 1; i >= 0; i--)
revS.push_back(s[i]);
// object from the class stringstream
int convertInt;
try
{
convertInt = stoi(revS);
}
catch (const out_of_range &oor)
{
cout << "out of range error: " << oor.what() << '\n';
return 0;
}
if (isNegative)
convertInt = convertInt * -1;
return convertInt;
}
};
int main()
{
Solution sol;
sol.reverse(-2147483648);
return 0;
}