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

leetcode 7. 反转整数(c++版)

2019-01-13 21:42 387 查看
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:
#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX-1)
int reverse(int x) {
int flag=x<0?-1:1;
int num=0;
while(x){
if((flag==-1&&(INT_MIN/10>num))||(flag==1&&INT_MAX/10<num))return 0;
num=num*10+x%10;
x/=10;
}
return num;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: