adding lecture 24
This commit is contained in:
24
leetcode/p7_reverse_integers.cpp
Normal file
24
leetcode/p7_reverse_integers.cpp
Normal file
@@ -0,0 +1,24 @@
|
||||
// leetcode problem 7: reverse integer
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
int reverse(int x) {
|
||||
int sign=1;
|
||||
if(x<0){
|
||||
sign = -1;
|
||||
}
|
||||
long result = 0;
|
||||
x = abs(x);
|
||||
// convert x to a string and reverse it
|
||||
string s = to_string(x);
|
||||
std::reverse(s.begin(),s.end());
|
||||
try{
|
||||
result = stoi(s);
|
||||
}catch(const std::out_of_range& e){
|
||||
cout<<"Error: "<<e.what()<<": out of range"<<endl;
|
||||
return 0;
|
||||
}
|
||||
result = sign * result;
|
||||
return result;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user