LeetCode_Simple_9. Palindrome Number

2019.1.12

前几天家里有点事耽搁了,今天继续刷刷刷!

题目描述:

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?

这题是判断一个数字是不是回文数,首先,如果一个数是负数,那它肯定不是回文数,在是正数的情况下,将这个数字进行翻转,如果翻转后的数字与原数字相同,则是一个回文数(可能有人会考虑翻转之后会不会溢出,其实如果是回文数,反转后仍是原数字,就不可能溢出,只要溢出一定不是回文数,返回false就行)

解法一:

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0) return false;
        else if(x%10==0&&x!=0) return false;
        else return Reverse(x)==x;
    }
    int Reverse(int x){
        int res=0;
        while(x!=0){
            if(res>INT_MAX/10) return -1;
            res=res*10+x%10;
            x/=10;
        }
        return res;
    }
};

不过执行时间好长,200ms。。。

解法二:

官方解法:

将数字本身反转,然后将反转后的数字与原始数字进行比较,如果它们是相同的,那么这个数字就是回文。 但是,如果反转后的数字大于int.MAX,我们将遇到整数溢出问题。

为了避免数字反转可能导致的溢出问题,为什么不考虑只反转 int 数字的一半?毕竟,如果该数字是回文,其后半部分反转后应该与原始数字的前半部分相同。

例如,输入 1221,我们可以将数字“1221”的后半部分从“21”反转为“12”,并将其与前半部分“12”进行比较,因为二者相同,我们得知数字 1221 是回文。

我们如何知道反转数字的位数已经达到原始数字位数的一半?

我们将原始数字除以 10,然后给反转后的数字乘上 10,所以,当原始数字小于反转后的数字时,就意味着我们已经处理了一半位数的数字。

class Solution {
public:
    bool isPalindrome(int x) {
     if(x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }
        int revertedNumber = 0;
        while(x > revertedNumber) {
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }
        return x == revertedNumber || x == revertedNumber/10;
    }
};
  • 时间复杂度:O(log10​(n)), 对于每次迭代,我们会将输入除以10,因此时间复杂度为O(log10​(n))。
  • 空间复杂度:O(1)。

执行用时112ms

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值