Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

Solution: Following is a straightforward solution. Using pow is not efficient, should always use mod operation.

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0) return false;
        int len = 0, tmp = x;
        while(tmp > 0) {
            tmp /= 10; ++len;
        }
        while(x > 0 && len > 0) {
            tmp = x / pow(10, len - 1);
            if(x % 10 != tmp) return false;
            x -= tmp * pow(10, len - 1); 
            x /= 10;
            len -= 2;
        }
        return true;
    }
};

Comments

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 8 Object-Oriented Design