leetcode Palindrome Number (判断整数是否为回文)

判断一个整数是否为回文,不使用额外空间。负数不被视为回文。通过翻转整数并与原数比较来解决,注意避免溢出问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

click to show spoilers.

Some hints:
Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

这题比较简单, 题目要求判断一个整数是不是回文, 回文的意思就是倒过来和原来一样, 比如1234321. 题目要求不能使用额外空间。
只要把整数翻转然后和原来的数比较就可以了, 负数不是回文(为什么啊)

code:

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

         return  res==x;
     }
};
  1. 不用考虑溢出, 直接从前后两端开始比较每个数字, 判断是否相等
    code
class Solution {  
//compare both the left most and the right most digit,   
//if not equal return false  
public:  
    bool isPalindrome(int x) 
    {  
      if(x<0)
        return false;
      int len=1;
      while( x/len >= 10)
      {
           len=len*10;

      }

      while(x!=0)
      {
       int left = x/len;
       int right = x%10;
       if( left!=right )
          return false;
       x = (x%len)/10;
       len=len/100;
      }

      return true;


     }  
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值