read
今天是第 19 天,要來寫的題目是 Palindrome Number 那麼話不多說,我們就開始吧 ─=≡Σ(((っ›´ω`‹ )っ!
# Example1
Input: x = 121
Output: true
# Example2
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.
# Example3
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Palindromic number 又稱做迴文數,先大概來摘要一下這題的重點:
- 將數字反轉後,內容還是相同
- 負數的狀況不成立,畢竟
-100
相反後並沒有100-
的值 - 尾數是 0 的話,反轉也不會成功
一開始不知道該怎麼下手,就先從最簡單的第二項不能是負數的下手吧!
func isPalindrome(x int) bool {
if x < 0 {
return false
}
return true
}
接下來就要思考,怎麼樣得到相反的值勒~ 應該可以使用跑迴圈的方式,透過每次取餘數的方式得到最後一個值再加總起來,這樣就能夠得到相反的數值了!
func isPalindrome(x int) bool {
if x < 0 {
return false
}
tmp := x
num := 0
for tmp > 0 {
remainder := tmp % 10
num = (num * 10) + remainder
tmp /= 10
}
res := x == num
return res
}
成功啦!
結尾
看起來 runtime 是有點點久還有待加強,但先有再求好XD 有任何問題歡迎與我告知 :)