Try first
题目
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
Subscribe to see which companies asked this question.
分析
首先,这是int,所以每个数可以直观的表示为 a*1+b*10+c*10*10+… …
因此,要将其reverse,只需让所求数从高位依次表示原来的数每次%10后的余数即可,即
anw = anw *10 + x%10;
x /= 10;
代码
class Solution
{
public:
int reverse(int x)
{
long long anw = 0;
while(x)
{
anw = anw *10 + x%10;
x /= 10;
}
return (anw <INT_MIN || anw >INT_MAX) ? 0 : anw ;
}
};