1. 程式人生 > >[LeetCode]9. Palindrome Number回文數

[LeetCode]9. Palindrome Number回文數

amp 也不會 reads war The bsp 之前 lean mine

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?

還是回文的問題,這題沒有給出數字的區間,不過我們不用擔心,回文數正反一樣所以反過來也不會溢出的,我們可以利用之前的整數翻轉的方法,如果回文reverse之後肯定相等

另外根據題意負數肯定是不回文的

class Solution {
    
public boolean isPalindrome(int x) { if(x<0) return false; if(x!=reverse(x)) return false; return true; } public int reverse(int x) { int res = 0,tag=0; while (x != 0) { tag = res * 10 + x % 10; if (tag / 10 != res) return 0; res
= tag; x = x / 10; } return res; } }

[LeetCode]9. Palindrome Number回文數