題目
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -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: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
翻譯
Palindrome 迴文,亦稱回文、回環,是正讀反讀都能讀通的句子。
也就是說給你一串數字,檢查是否為回文,比如給你 12321、11、22 都是回文,
但是個位數字就不是回文了。
額外條件問你能不能不用轉成字串的方法反轉完成。
思維
最後的比對如果是回文,反轉以後應該也是相同。
實作
先來個字串反轉版的。
fun isPalindrome(x: Int): Boolean {
val num: String = Integer.toString(x)
val reverse: String = num.reversed()
return num == reverse
}
接著透過不是字串反轉的方式。
fun isPalindrome(x: Int): Boolean {
if(x < 0 || x > Int.MAX_VALUE) return false
var temp = x
var reverse = 0
while(temp > 0) {
reverse = reverse * 10 + temp % 10
temp /= 10
}
return x == reverse
}