Leetcode刷题(3)整数反转
生活随笔
收集整理的這篇文章主要介紹了
Leetcode刷题(3)整数反转
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最好的種樹是十年前,其次是現在。歌謠?每天一個前端小知識?提醒你改好好學習了?知乎博主 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 } };運行結果
?
?
總結
以上是生活随笔為你收集整理的Leetcode刷题(3)整数反转的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (送书和红包)快人一步,掌握前端函数式编
- 下一篇: 安卓小程序——猜数字游戏