[LeetCode]9. Palindrome Number回文数

Posted jchen104

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]9. Palindrome Number回文数相关的知识,希望对你有一定的参考价值。

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回文数的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-9-Palindrome Number

LeetCode 9. Palindrome Number

leetcode 9. palindrome number

#Leetcode# 9. Palindrome Number

LeetCode 9. Palindrome Number

LeetCode - 9 - Palindrome Number