题目:
Leetcode:9. Palindrome Number

描述:

  • 内容:Determine whether an integer is a palindrome. Do this without extra space.
  • 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.

  • 题意:确定一个数是回文数:
    1、负数不存在回文数;
    2、不能够申请新的内存空间;
    3、逆序可能会导致数字移除;

分析:

  • 思路:
    1、利用long long来存储 逆序的数,在进行比较;
    2、将回文数分成中值前后的两部分再进行比较,后一部分逆序和前面的数字比较。

代码:

bool isPalindrome(int x) {
    // 实现方法一:
    long long nValue = 0;
    int nTemp = x;
    if (nTemp < 0)
    {
        return false;
    }
    while (0 != nTemp / 10)
    {
        nValue = nValue * 10 + nTemp % 10;
        nTemp /= 10;
    }
    nValue = nValue * 10 + nTemp % 10;
    if (nValue == x)
    {
        return true;
    }
    return false;
}

bool isPalindromeEx(int x) {
    // 实现方法二:
    if (x < 0)
    {
        return false;
    }
    int nLen = 0;
    int nTemp = x;
    while (0 != nTemp)
    {
        nTemp /= 10;
        ++nLen;
    }
    nTemp = x;
    int nValue = 0;
    int nHalf = nLen / 2;
    while (0 != nHalf)
    {
        nValue = nValue * 10 + (nTemp % 10);
        nTemp /= 10;
        --nHalf;
    }
    
    // 若为奇数回文数还需去掉最中间的数位,也就是当前数的末尾一位
    if (1 == nLen % 2)
    {
        nTemp /= 10;
    }
    return nTemp == nValue;
}

bool isPalindromeEx1(int x) {
    if (x < 0)
    {
        return false;
    }
    int nValue = 0;
    // 较方法二做了改进
    while (x > nValue)
    {
        nValue = nValue * 10 + (x % 10);
        x /= 10;
    }

    return (x == nValue) || (x == (nValue / 10));
}
内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!