题目描述(Easy)
Given a 32-bit signed integer, reverse digits of an integer.
题目链接
https://leetcode.com/problems/reverse-integer/description/
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) {
if (x == INT_MIN) return 0;
int res = 0;
int y = x > 0 ? x : -x;
bool sign = x > 0 ? true : false;
for (; y; y /= 10)
{
if ((INT_MAX - y % 10) / 10 < res)
return 0;
res = 10 * res + y % 10;
}
return sign ? res : -res;
}
};