【LeetCode刷题记录】9. Palindrome Number

Description:

Determine whether an integer is a palindrome. Do this without extra space.

这道题目实现并不难,但题目要求空间复杂度为O(1), 有一定的技巧性。

Solutions:

Solution 1:

public boolean isPalindrome(int x) {
        int palindromeX = 0;
        int inputX = x;
        while(x>0){
            palindromeX = palindromeX*10 + (x % 10);
            x = x/10;
        }
        return palindromeX==inputX; 
    }

受到LeetCode 7.Reverse Integer 的启发,将原int型的数据完全反转后,比较反转后的数据与原数据是否相同,相同则为回文,反之不是。

Question:这个算法没有考虑到int型数据反转后可能存在的溢出情况,是不是有错误?
Answer: 若反转后的数据比原数据大,那么它一定与原数据不相同,肯定不是回文了,所以这个算法隐性地排除了溢出的情况。

但进一步思考,判断是否为回文需要将整个数字完全反转吗?反转到一半不久可以进行比较了吗?这就引出了Solution 2。

Solution 2:

bool isPalindrome(int x) {
        if(x<0|| (x!=0 &&x%10==0)) return false;
        int sum=0;
        while(x>sum)
        {
            sum = sum*10+x%10;
            x = x/10;
        }
        return (x==sum)||(x==sum/10);
    }

这个算法要额外考虑能被10整除的数,需要特别注意。

Solution 3:

bool isPalindrome(int x) {
          //negative number
          if(x < 0)
              return false;

          int len = 1;
         while(x / len >= 10)
             len *= 10;

         while(x > 0) {  
             //get the head and tail number
             int left = x / len;
             int right = x % 10;

             if(left != right)
                 return false;
             else{
                 //remove the head and tail number
                 x = (x % len) / 10;
                 len /= 100;
             }
         }       
         return true;
     }

解题思路: 每次提取头尾两个数,判断它们是否相等,判断后去掉头尾两个数。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值