Problem
Reverse digits of a 32-bit signed integer. When the reversed integer overflows return 0. Optimized code here.
Feedback
I'm looking for any ways I can optimize this with modern C++ features overall. I hope my use of const-correctness, exception handling, and assertions is implemented well here, please let me know. Is there any way I can use byte operations to reverse the int and keep track of the sign possibly?
Based on the submission feedback from LeetCode, is it safe to say that the time complexity is \$O(n)\$ and space complexity is \$O(n)\$? If I can reduce the complexity in anyway would love to know!
#include <cassert>
#include <climits>
#include <stdexcept>
#include <string>
class Solution
{
public:
int reverse(int i) {
bool is_signed = false;
if(i < 0) { is_signed = true; }
auto i_string = std::to_string(i);
std::string reversed = "";
while(!i_string.empty()) {
reversed.push_back(i_string.back());
i_string.pop_back();
}
try {
i = std::stoi(reversed);
} catch (const std::out_of_range& e) {
return 0;
}
if(is_signed) { i *= -1; }
return i;
}
};
int main()
{
Solution s;
assert(s.reverse(1) == 1);
assert(s.reverse(0) == 0);
assert(s.reverse(123) == 321);
assert(s.reverse(120) == 21);
assert(s.reverse(-123) == -321);
assert(s.reverse(1207) == 7021);
assert(s.reverse(INT_MAX) == 0);
assert(s.reverse(INT_MIN) == 0);
}
120
is21
, how can you know whether 'the' reverse of21
should be120
or12
? What makes 'the' reverse of1
number1
and not10000
? How can you tell your code solves the problem if the correct solution is not defined? \$\endgroup\$