iT邦幫忙

0

Leet Code 2. Two Numbers

  • 分享至 

  • twitterImage
  •  

題目
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

翻譯
給定一個帶符號的32位元x,請返回x,並讓數字相反。
如果反轉x導致該值超出32位元範圍[-231、231-1],則返回0。

提示:
Input: x = 123
Output: 321

Input: x = -123
Output: -321

Input: x = 120
Output: 21

有注意到反轉後的數可能會超過範圍嗎,例如說1000000003反轉後就超過了32位元的integer。這種情況要怎麼處理?

在這個問題中,超過integer只要回傳0就可以。

加深容易混雜的語法
parseInt() 函数:可解析一個字符串,並返回一個整數。
toString() 函数:可把一个 Number 對象轉換為一個字符串,並返回結果
Math.pow(base, exponent) 函数:第一個參數為原始值,第二個參數為次方
ex:Math.pow(7, 2); // 49
ex:Math.pow(4, 0.5); // 2

Math.sign() 函数:只會返回正數或負數,+ / -
ex:Math.sign(1010); // 1
ex:Math.sign(-0); // -1
ex:Math.sign(0); // 0
ex:Math.sign('-3'); // -1

思路
先把數字轉成string後並反轉,在判斷res是否超出32位元的integer,

/**
 * @param {number} x
 * @return {number}
 */
const reverse = function (x) {
    let res = parseInt ( x.toString().split('').reverse().join('') );
    
    if( res > Math.pow (2, 31) -1 ) {
        return 0;
    }
    return Math.sign (x) * res;
};

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
koro_michael
iT邦新手 2 級 ‧ 2021-03-04 11:57:21

JS 會 51- 這種字串也能正確轉成數字,厲害

我要留言

立即登入留言