Leetcode c语言-Palindrome Number

来源:互联网 发布:去黑眼圈的产品知乎 编辑:程序博客网 时间:2024/05/20 07:53

Title:

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

click to show spoilers.

Some hints:

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 i,m,n,p,q;    int result;    int temp;        if (x<0)        return 0;        for (i=10;i>=1;i--) {        temp =x/(pow(10,i-1));        if (temp)           break;    }    if (i==1) /*一个数字*/        return 1;    if (i%2 == 0) {        m = i/2;        n = i/2 + 1;        while (m>=1) {            p = x/pow(10,m-1);            q = x/pow(10,n-1);            if (p%10 != q%10) {                result = 0;                break;            }            else                result = 1;            m--;            n++;        }    }    else if (i%2 != 0) {        m = i/2;        n = i/2 +2;         while (m>=1) {            p = x/pow(10,m-1);            q = x/pow(10,n-1);            if (p%10 != q%10) {                result = 0;                break;            }             else                 result =1;            m--;            n++;        }    }        return result;}



原创粉丝点击