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

LeetCode:07: Reverse Integer

2017-09-24 21:02 441 查看

题目描述:

(C++实现)

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

lick 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.

题目分析:

输入一个32位有符号的整形,返回这个数字的倒序,越界返回0。

代码实现:

class Solution {
public:
int reverse(int x) {
int y1=x,y2;
long res=0;
if(x>2147483647||x<-2147483647){
return 0;
}
while(y1!=0){
y2=y1%10;
res=res*10+y2;
//多加一个判断为了提高效率
if(res>2147483647||res<-2147483647){
return 0;
}
y1=y1/10;
}
if(res>2147483647||res<-2147483647){
return 0;
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 leetcode