leetcode:Palindrome Number 回文数的判定


date: 2018-09-28 09:07:00+00:00
原标题: leetcode:Palindrome Number 回文数的判定
原链接: https://www.dreamoftime0.com/2018/09/28/leetcodepalindrome-number-%e5%9b%9e%e6%96%87%e6%95%b0%e7%9a%84%e5%88%a4%e5%ae%9a/

题目:

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true
Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:

Coud you solve it without converting the integer to a string?

解法1:

作为字符串处理,判断反转后是否和原来一致

class Solution {
public:
    bool isPalindrome(int x) {
        string str=to_string(x);
        string str0=str;
        reverse(str.begin(),str.end());
        return str == str0;
    }
};

解法2:

作为数字处理,前半部分和反转后的后半部分比较,如果相同(x的位数为偶数)或大的部分除以10后相同(x的位数为奇数),则说明为回文数。

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0 || (x%10==0 && x!=0))
            return false;

        int tmp=0;
        while(x>tmp){
            tmp=tmp*10+x%10;
            x/=10;
        }

        return x==tmp || x==tmp/10;

    }
};

测试程序:

/*

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true
Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:

Coud you solve it without converting the integer to a string?

*/

#include
#include

using namespace std;

class Solution {
public:
    bool isPalindrome(int x) {
        /*
        if(x<0 || (x%10==0 && x!=0))
            return false;

        int tmp=0;
        while(x>tmp){
            tmp=tmp*10+x%10;
            x/=10;
        }

        return x==tmp || x==tmp/10;
        */
        string str=to_string(x);
        string str0=str;
        reverse(str.begin(),str.end());
        return str == str0;
    }
};

int main(){
    Solution s;

    cout<

你可能感兴趣的:(C/C++,leetcode,回文数)