Leetcode 7. Reverse Integer
程序员文章站
2022-07-15 14:38:59
...
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
- Two loops
class Solution {
public:
int reverse(int x) {
if(x == 0 || x == INT_MIN) {
return 0;
}
int remainder = 0;
int y = abs(x);
queue<int> number;
while(y) {
remainder = y % 10;
number.push(remainder);
y /= 10;
}
int result = 0;
while(!number.empty()) {
if((INT_MAX - number.front()) / 10 < result) {
return 0;
}
result = result * 10 + number.front();
number.pop();
}
return x == abs(x)?result:-result;
}
};
- One loop
class Solution {
public:
int reverse(int x) {
if(x == 0 || x == INT_MIN) {
return 0;
}
int y = abs(x);
int result = 0;
int remainder = 0;
while(y) {
remainder = y % 10;
if((INT_MAX - remainder) / 10 < result) {
return 0;
}
result = result * 10 + remainder;
y /= 10;
}
return x == abs(x)?result:-result;
}
};
Reference
上一篇: 7. Reverse Integer
下一篇: shellcode初识