Skip to content
Rain Hu's Workspace
Go back

[Leetcode] 9. Palindrome Number

Rain Hu

9. Palindrome Number


一、題目

Given an integer x, return true if x is palindrome number.
An integer is a palindrome when it reads the same backward as forward.

Example 1:

Example 2:

Example 3:

Constraints:

Follow up: Could you solve it without converting the integer to a string?


二、分析

三、解題

1. Math

bool isPalindrome(int x) {
    if (x < 0) return false;
    if (x < 10) return true;
    if (x % 10 == 0) return false;
    
    int rev = 0;
    while (x > rev) {
        rev = 10 * rev + x % 10;
        x /= 10;
    }
    return rev == x || rev/10 == x;
}

回目錄 Catalog


Share this post on:

Previous
[Leetcode] 10. Regular Expression Matching
Next
[Leetcode] 8. String to Integer (atoi)