#Leetcode# 7. Reverse Integer
https://leetcode.com/problems/reverse-integer/description/
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
代码:
class Solution {
public:
int reverse(int x) {
long long ans = 0;
int flag = 1;
if(x < 0) {
flag = -1;
x = abs(x);
}
while(x > 0) {
ans = ans * 10 + x % 10;
x /= 10;
}
if(ans > INT_MAX) return 0;
else if(flag < 0) return -ans;
else return ans;
}
};

浙公网安备 33010602011771号