LeetCode 9. Palindrome Number回文数判断

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.

Difficulty:Easy


分析:

首先,负数和以0结尾的数可以排除掉,直接返回FALSE;
然后,根据输入数据的左右部分是否相等,从而判断出回文数。
这里主要用到一个循环,利用求余数法,不断将余数×10,得到右边倒序过来的数据,直至该结果大于等于左边剩下的数。
最后,判断两边的数是否相等,若相等,则说明是回文数,返回TRUE;否则返回FALSE。


代码如下:

#include <iostream>
using namespace std;
class Solution {
public:
    bool isPalindrome(int x) {
        // 负数以及以0结尾的数
        if (x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }
        int reverseNumber = 0;
        // 循环结束条件:右边的数大于等于左边的数
        while (x > reverseNumber) {
            reverseNumber = reverseNumber * 10 + x % 10;
            x = x / 10;
        }
        // 两边数相等,如1221,此时x=12=reverseNumber;
        // 两边不相等,如12321,此时x=12,reverseNumber=123
        return x == reverseNumber || x == reverseNumber / 10;
    }
};
int main() {
    Solution s;
    int x;
    cin >> x;
    cout << s.isPalindrome(x) << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值