LeetCode9. 回文数

LeetCode9. 回文数:

题目描述:

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。

回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
例如,121 是回文,而 123 不是。

示例 1:
输入:x = 121
输出:true

示例 2:
输入:x = -121
输出:false
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:
输入:x = 10
输出:false
解释:从右向左读, 为 01 。因此它不是一个回文数。

提示:
-2^31 <= x <= 2^31 - 1

思路:

1.转换成字符串:翻转一下跟原来的做对比看是否一致
2.将数值进行翻转,对比是否一致

自己写的代码:

思路对了,但是做了很多冗余的判断,很慢,击败8.66%,hh

class Solution {
public:
    bool isPalindrome(int x) {
        int res = 0;
        int temp = x;
        if(x < 0) return false;
        while(x)
        {
            if(res > (INT_MAX - x % 10) / 10) return false;
            res = res * 10 + x % 10;
            x /= 10;
        }
        printf("%d", res);
        if(res == temp) return true;
        else return false;
    }
};

转成字符串判断:

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0) return 0;
        string s = to_string(x);
        return s == string(s.rbegin(), s.rend());
    }
};

数值转换方法:

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0 ) return 0;
        int y = x;
        long long res = 0;
        while(x)
        {
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res == y;
    }
};

你可能感兴趣的:(LeetCode9. 回文数)