LeetCode 9. Palindrome Number回文数判断

来源:互联网 发布:微软sql认证 编辑:程序博客网 时间:2024/06/11 21:46

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;}
原创粉丝点击