您的位置:首页 > 其它

LeetCode-7. Reverse Integer

2018-02-27 12:22 363 查看

Description

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 hold
integers within the 32-bit signed integer range. For the purpose of
this problem, assume that your function returns 0 when the reversed
integer overflows.


Solution 1(C++)

class Solution {
public:
int reverse(int x) {
long res=0;
while(x!=0){
int a=x%10;
x/=10;
res=res*10+a;
}
return res>INT_MAX||res<INT_MIN ? 0 : res;
}
};


Solution 2(C++)

class Solution {
public:
int reverse(int x) {
int ans = 0;
while (x) {
int temp = ans * 10 + x % 10;
if (temp / 10 != ans)
return 0;
ans = temp;
x /= 10;
}
return ans;
}
};


算法分析

两种方法大同小异,主要是判断是否越界的方法需要注意。

程序分析

略。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: