leetCode_Reverse Integer

一、 题目描述:

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

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

二、

解题思路:

在取每个位置上的数字同时将之前所求得数字的和上升一位,具体来说在取出个位上的数字同时,准备将他放到最高位。

即:边取数,边构造新数。

源代码如下:


//遇到溢出问题。
class Solution {
public:
int reverse(int x) {
int res=0;
while(x!=0)
{
if(abs(res)>INT_MAX/10)//在溢出之前进行判断,防止溢出。
{
return 0;
}
res=res*10+x%10;
x/=10;
}
return res;
}

};

三、

总结:

1:注意防止溢出的方法,在每次取数构成新数的同时,通过查看旧数的取值范围来确定是否越界。

2:一趟循环完成所有任务的思路,需要养成。

原文地址:https://www.cnblogs.com/zydxx/p/9959805.html