leetcode/src/s0007_reverse_integer.cpp

21 lines
363 B
C++
Raw Normal View History

2022-11-02 13:34:49 +00:00
#include "s0007_reverse_integer.hpp"
2022-11-30 10:20:36 +00:00
int S0007::reverse(int x) {
2022-11-02 13:34:49 +00:00
int r{0};
std::queue<int> queue;
while (x != 0) {
queue.push(x % 10);
x = static_cast<int>((x - (x % 10)) / 10);
}
while (!queue.empty()) {
if (r < INT_MIN / 10 || r > INT_MAX / 10) {
return 0;
}
r = r * 10 + queue.front();
queue.pop();
}
return r;
}