最好的种树是十年前,其次是现在。歌谣 每天一个前端小知识 提醒你改好好学习了 知乎博主 csdn博主 b站博主 放弃很容易但是坚持一定很酷 我是歌谣 喜欢就一键三连咯 你得点赞是对歌谣最大的鼓励
1题目
给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
示例 1:
输入:x = 123
输出:321
示例 2:
输入:x = -123
输出:-321
示例 3:
输入:x = 120
输出:21
示例 4:
输入:x = 0
输出:0
提示:
-231 <= x <= 231 - 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
代码部分
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
if (x <= (-Math.pow(2, 31)) && x >= (Math.pow(2, 31) - 1)) {
return 0;
}
else if ((-Math.pow(2, 31))<=x&&x< 0) {
//1先转换为字符串
const geyao1 =x.toString().slice(1)
//console.log(geyao1, 'geyao1')
//数组分割
const geyao2 = Array.from(geyao1)
//console.log(geyao2, 'geyao2')
//反过来
const geyao3 = geyao2.reverse()
//console.log(geyao3, 'geyao3')
//拼接
const geyao4 = '-'+Number(geyao3.join(''))
console.log(geyao4, 'geyao4')
if(geyao4<= (-Math.pow(2, 31))){
return 0
}
return geyao4
} else if((Math.pow(2, 31))>=x&&x> 0) {
//1先转换为字符串
const geyao1 =x.toString()
//console.log(geyao1, 'geyao1')
//数组分割
const geyao2 = Array.from(geyao1)
//console.log(geyao2, 'geyao2')
//反过来
const geyao3 = geyao2.reverse()
//console.log(geyao3, 'geyao3')
//拼接
const geyao4 = Number(geyao3.join(''))
console.log(geyao4, 'geyao4')
if(geyao4>= (Math.pow(2, 31))){
return 0
}
return geyao4
}else if(x===0){
return 0
}
};
运行结果

浙公网安备 33010602011771号