文章目录[隐藏]
7. Reverse Integer
- Easy
Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment that 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.
- Example 1:
Input: x = 123
Output: 321
- Example 2:
Input: x = -123
Output: -321
- Example 3:
Input: x = 120
Output: 21
- Example 4:
Input: x = 0
Output: 0
- Constraints:
-2^31 <= x <= 2^31 - 1solution
My Way
我想的是利用除留余数法,获取每个数字,并统计位数,然后再反过来进行运算得到我们需要的结果;我这个比较容易理解
JAVA
class Solution {
public int reverse(int x) {
int num = 0;//the count of number in x;
int y = x;
do{
num++;
y = y / 10;
}while(y != 0 );
num--;
long ret = 0;
do{
ret = ret + (int) ( (x % 10) * Math.pow(10,num) );//如果为1534236469得到的结果会超出int的范围,必须提前判断!
num--;
x = x / 10;
}while(x != 0);
if( ret > Math.pow(2,31)-1 || ret < -Math.pow(2,31)){
return 0;
}
return (int)ret;
}
}
Python
注意两点:// 和 /的区别
class Solution:
def reverse(self, x: int) -> int:
if x < 0:
x = -x
flag = 1
else:
flag = 0
num = 0
y = x
z = x
while(y != 0):
num += 1
x = y % 10
y = y // 10
num -= 1
ret = 0
while(z != 0):
ret = ret + (z % 10) * math.pow(10,num)
num -= 1
z = z // 10
if( ret > math.pow(2,31)-1 or ret < -math.pow(2,31)):
return 0
if(flag == 1):
ret = -ret
return int (ret)
The best way I found in leetcode
Java
这个用了类似“栈”的概念,这个到好说,只是这个计算数据的方法倒是第一次见到,感兴趣的可以区看看原文解释:https://leetcode.com/problems/reverse-integer/solution/
- 它这里的数据表示方式:
321 = { (0 x 10 + 3) x 10 + 2 } x 10 + 1
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}
python3
没看懂,自己去了解!
class Solution:
def reverse(self, x: int) -> int:
x = str(x)
a = int('-' + x[-1:0:-1]) if x[0] == '-' else int(x[::-1])
if a >= -2147483648 and a<= 2147483647: return a
else: return 0