[9] Palindrome Number

© Jarvus Chen / www.jarvus.net

Description

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

Required knowledge

Palindrome number means a sequence repeat beginning character to the ending part.

Example: 11, 121, 12321...

My solution

It's a very simple test.

bool isPalindrome(int x) {

    if ( x < 0 ){
        return false;
    }

    // get the amount of the input value
    int temp = x;
    int count = 0;
    while ( temp > 0 ){
        count++;
        temp = temp/10;
    }

    // process by char array
    char* s = malloc(count);
    sprintf(s,"%i",x);

    // check starting and ending number in the same time
    for(int i = 0; i < count/2; i++){
        if ( s[i] !=  s[count-1-i] ){
            return false;
        }
    }
    return true;
}

Others solution

https://discuss.leetcode.com/topic/14436/32ms-c-language-solution

Reverse the input integer and then compare is it match with original input.

It didn't check bound because of the input value can't be a overflow value.

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

    return x == y;
}

results matching ""

    No results matching ""