7. Reverse Integer
题目描述
讲一个数字高位低位反转,返回新的数字
如果新的数字超出范围则返回0
思路
比较简单的思路,高低位置反转也就意味着最低位将成为最高,那么我们每次取出一位最低存入新数中,然后再取的就接在他后面,知道旧数字取完。
代码
class Solution {
public:
int reverse(int x) {
int result, temp;
result = 0;
temp = 0;
// while x != 0
while (x) {
// 判断结果超出范围,返回0
if (result > 214748364 || result < -214748364) {
result = 0;
break;
}
// result 每次循环增大10倍然后加入x中的一位
result *= 10;
temp = x % 10;
if (temp != 0) {
result += temp;
// printf("%d;%d;%d\n",x ,temp,result);
}
// x除10去除最低位
x = x / 10;
}
return result;
}
};