- 题目描述:
- 题目链接:
-视频讲解链接B站视频讲解
- 复杂度分析:
- 代码:
c++版本:
class Solution {
public:
/**
*
* @param x int整型
* @return int整型
*/
int reverse(int x) {
// write code here
int res = 0;//用于返回最终结果
while(x!= 0){
if(res < INT_MIN / 10 || res > INT_MAX / 10){
//如果越界就知己返回溢出结果
return 0;
}
//求反转后的数字
int num = x % 10;
x /= 10;
res = res * 10 + num;
}
return res;
}
};
Java版本:
import java.util.*;
public class Solution {
/**
*
* @param x int整型
* @return int整型
*/
public int reverse (int x) {
// write code here
int res = 0;//用于返回最终结果
while(x!= 0){
if(res < Integer.MIN_VALUE / 10 || res > Integer.MAX_VALUE / 10){
//如果越界就知己返回溢出结果
return 0;
}
//求反转后的数字
int num = x % 10;
x /= 10;
res = res * 10 + num;
}
return res;
}
}Python版本:
#
#
# @param x int整型
# @return int整型
#
class Solution:
def reverse(self , x ):
# write code here
MAX, MIN = (2**31 - 1), -(2 ** 31)
flag = True if x >= 0 else False
res = 0#用于返回最终结果
while x != 0:
if flag == True:
#求反转后的数字
num = x % 10
x //= 10
else:
#求反转后的数字 python负数需要下面这样处理
num = x % (-10)
x = -(x//-10)
if res < (MIN//10) or res > (MAX // 10):#如果越界就知己返回溢出结果
return 0
res = res * 10 + num
return res;JavaScript版本:
/**
*
* @param x int整型
* @return int整型
*/
function reverse( x ) {
// write code here
let MAX = 2147483647;
let MIN = -2147483648;
let res = 0;//用于返回最终结果
while(x!= 0){
if(res < parseInt(MIN / 10) || res > parseInt(MAX / 10)){
//如果越界就知己返回溢出结果
return 0;
}
//求反转后的数字
let num = x % 10;
x = parseInt(x/10);
res = res * 10 + num;
}
return res;
}
module.exports = {
reverse : reverse
};
京公网安备 11010502036488号