iT邦幫忙

0

【ruby】leetcode 練習 :Palindrome Number

  • 分享至 

  • xImage
  •  

給定一個整數x,如果x是回文整數則返回true。

當一個整數向後讀和向前讀一樣時,它就是一個回文數。

Example 1:

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

Example 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.

Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

方法一:反轉字串

def is_palindrome(x)
    if x < 0
        return false
    else
        string = x.to_s
        if string == string.reverse
            return true
        else
            false
        end
    end
end

方法二 反轉數字

def is_palindrome(x)
    temp = x
    reverseNumber = 0
    
    while temp > 0
        rightNumber = temp % 10
        reverseNumber = reverseNumber * 10 + rightNumber
        temp /= 10
    end
    
    if x == reverseNumber
        true
    else
        false
    end
end

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

尚未有邦友留言

立即登入留言