iT邦幫忙

0

Leet Code 9. Palindrome Number

  • 分享至 

  • xImage
  •  

題目
Determine whether an integer is a palindrome. Do this without extra space.

Some hints: Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

翻譯
判斷一個int整數是否是自己的迴文數,不能使用額外的空間來操作。

提示:
負整數會是自己的迴文數嗎(ex. -1)

如果你想用字串來解是不行的,因為不能使用額外的空間。

你也可以反轉整數,如果你之前已經做過LeetCode 7. Reverse Integer,你會知道反轉後的數可能會超過integer的最大值。

範例1
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

範例2
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

解題

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
    var reverse = 0;
    var copy = x;

    while (copy > 0) {
      const digit = copy % 10; 
      //i=1 => 1141 % 10 = 1 | i=2 => 114 % 10 = 4 | i=3 => 11 % 10 = 1 | i=4 => 1 % 10 = 1

      reverse = reverse * 10 + digit; 
      // i=1 => 0 * 10 + 1 = 1 | i=2 => 1 * 10 + 4 = 14 | i=3 => 14 * 10 + 1 = 141 | i=4 => 141 * 10 + 1 = 1411

      copy = Math.floor(copy / 10); 
      // i=1 => 1141/10 = 114 | i=2 => 114/10 = 11 | i=3 => 11/10 = 1 | i=4 => 1/10 = 0
    }
    return reverse === x;
};

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

尚未有邦友留言

立即登入留言