给一个正整数,把它反转过来,不考虑超界
用例:
123 -> 321
//第一种基本方法,把每位数取出来,再计算回去
long getTen(int n)
{
if (n == 1) {
return 1;
} else {
return 10 * getTen(n - 1);
}
}
long reverse_x(long x)
{
int index = 0;
char digit_arr[15];
long result = 0;
while (x > 0) {
digit_arr[index++] = x % 10;
x = x / 10;
}
for (int i = 0; i < index; i++) {
result = result + digit_arr[i] * getTen(index - i);
}
return result;
}
//利用小技巧,迭代计算
long reverse_x2(long x)
{
long ret = 0;
while (x) {
ret = ret * 10 + x % 10;
x /= 10;
}
return ret;
}
LeeCode:Reverse Integer