您的位置:首页 > 其它

[LeetCode] 7. Reverse Integer 翻转整数

2018-03-01 16:01 447 查看

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.

 

注意:OJ更新了溢出测试,所以还是要考虑溢出。

Java:

public class Solution {
public int reverse(int x) {
long result = 0;
int tmp = Math.abs(x);
while(tmp>0){
result *= 10;
result = result * 10 + tmp % 10;
if(result > Integer.MAX_VALUE){
return 0;
}
tmp /= 10;
}
return (int)(x>=0?result:-result);
}
}

Python:

class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x < 0:
return -self.reverse(-x)

result = 0
while x:
result = result * 10 + x % 10
x //= 10
return result if result <= 0x7fffffff else 0  # Handle overflow.

C++:

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;
}
};

C++:

class Solution {
public:
int reverse(int x) {
int result = 0;
while (x) {
auto prev = result;
result *= 10;
result += x % 10;
if (result / 10 != prev) {
result = 0;
break;
}
x /= 10;
}
return result;
}
};

 

类似题目:

[LeetCode] 190. Reverse Bits 翻转二进制位

 

All LeetCode Questions List 题目汇总

  

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