您的位置:首页 > 编程语言 > C语言/C++

LeetCode 7. Reverse Integer

2017-06-12 21:43 190 查看
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.
题目要求很简单,对整数进行反转。需要注意的一点是,当超出了整型的范围,即INT_MIN~INT_MAX之间的话,需要返回0。但是y不能直接和INT_MIN以及INT_MAX进行比较。因此需要在对y赋值前与INT_MAX/10以及INT_MIN/10进行比较,如果超出范围则返回10。代码实现如下:

class Solution {
public:
int reverse(int x) {
int y = 0;
while(x != 0){
if(y > INT_MAX/10 || y < INT_MIN/10)
return 0;
y = y*10+x%10;
x = x/10;
}
return y;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ Reverse Integer