[LeetCode-9] Palindrome Number(回文数)

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

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

bool isPalindrome(int x) {
    int numLen  = 0;
    int i= 0;
    char *str = NULL;
    int temp = x; 
    if(x < 0)
        return 0;
    /*1.计算位数*/
    while(temp) {
        numLen ++;
        temp = temp/10;     
    }

    /*2.申请空间,注意结束标志位*/
    str = (char *)malloc(numLen+1);

    if(!str)
        return 0;

    /*3.转换成字符串格式*/
    for (i = 0;i < numLen;i++) {
        temp= x%10;
        str[i] =temp+'0';
        x = x/10;
    }

    str[i] = '\0';
    i = 0;
    int count = numLen/2;

    /*4.判断是否为回文数*/
    while(count) {
        if(str[i] != str[numLen-i-1]) {
            free(str);
            return 0;
        }
        count --;
        i ++;
    }
    free(str);
    return 1;
}

你可能感兴趣的:(回文数操作)