美文网首页算法提高之LeetCode刷题
【LeetCode每日一题】9. Palindrome Numb

【LeetCode每日一题】9. Palindrome Numb

作者: 七八音 | 来源:发表于2020-04-14 16:22 被阅读0次

9. Palindrome Number

问题描述

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.

给定一个数字判断这个数字是否是回文数。回文数的定义:正着读和反着读,两个数字一样。

解析

常见解法是通过将原始数字x翻转得到reverseX,然后通过比较两个数字是否相等给出最终答案。

但是翻转过程中,要注意数据溢出。

通过给出的例子,我们可以知道:

  1. 所有的负数都不是回文数;
  2. 正数有可能是回文数;
  3. 0 是回文数。

为了方便运算,减少数字越界带来的麻烦,可以使用更大的数据类型来进行数字存储,如long long型。

答案

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        
        int t = x;
        long long y = 0;
        while (x){
            y = y * 10 + (x % 10);
            x /= 10;
        }
        
        return ((y-t) == 0);//隐式类型转换
    }
};

另一种方法是,在翻转数字时考虑到数字越界。

越界标准是:y > INT_MAX/10 || (y == INT_MAX/10 && val > 7)

因为当y > INT_MAX/10时,下一次乘以10之后,结果一定会越界;如果恰好等于INT_MAX/10,而且val >7 时,也会越界(INT_MAX=2147483647);如果等于7,继续运算,下一次循环时y一定大于INT_MAX/10。

具体代码如下:

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        
        int y = 0, t = x;
        
        while (x){
            int val = x % 10;
            x /= 10;
            if (y > INT_MAX/10 || (y == INT_MAX/10 && val > 7 ))
                return false;
            y = y * 10 + val;
        }
        return y == t;
    }
};

相关文章

网友评论

    本文标题:【LeetCode每日一题】9. Palindrome Numb

    本文链接:https://www.haomeiwen.com/subject/ooetvhtx.html