LintCode 491: Palindrome Number

  1. Palindrome Number

Check a positive number is a palindrome or not.

A palindrome number is that if you reverse the whole number you will get exactly the same number.

Example
Example 1:

Input:11
Output:true

Example 2:

Input:1232
Output:false
Explanation:
1232!=2321
Notice
It’s guaranteed the input number is a 32-bit integer, but after reversion, the number may exceed the 32-bit integer.

解法1:

class Solution {
public:
    /**
     * @param num: a positive number
     * @return: true if it's a palindrome or false
     */
    bool isPalindrome(int num) {
        string numStr = to_string(num);
        int n = numStr.size();
        
        int start = 0, end = n - 1;
        while(start < end) {
            if (numStr[start] != numStr[end]) return false;
            start++;
            end--;
        }
        return true;
    }
};

解法2:

class Solution {
public:
    /**
     * @param num: a positive number
     * @return: true if it's a palindrome or false
     */
    bool isPalindrome(int num) {
        int temp = num; //num = 321
        long long rev = 0;
        while(temp) {
            rev = rev * 10 + temp % 10;
            temp /= 10;
        }
        
        return rev == num;
    }
};

你可能感兴趣的:(LintCode 491: Palindrome Number)