Wednesday 12 July 2017

9. Palindrome Number

Determine whether a given integer is a palindrome or not. Do this without extra space.
Note that the negative integers are assumed to be non-palindromic. Also, you are not allowed to convert the integer to string, given the restriction of using extra space.

Approach:

Return false if the given integer is negative. Otherwise, reverse the given integer and return true if the reversed integer and the given integer are both same else false.
class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0)
            return false;
        
        int rem, revX = 0;
        int temp = x;
        while(temp > 0){
            rem = temp % 10;
            revX = revX * 10 + rem;
            temp = temp / 10;
        }
        return revX == x;
    }
};

Here is the link to ideone solution : http://ideone.com/9YyJke
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive