leetcode 9 给一个int类型的数字,判断是否是回文数

不使用额外空间,判断一个int类型的整数是否为回文。考虑负数的情况以及反转可能导致的溢出问题。通过取余数和首位数比较来实现。

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

leetcode 9 给一个int类型的数字,判断是否是回文数

题目要求:

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

Could negative integers be palindromes? (ie, -1)  负数返回false

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? 当使用了反转一个int类型的数据时,考虑会不会溢出

代码:

因为不可以申请新的空间,也最好不要反转int数字,那么考虑将x每次除以10得到余数,和x/(len-1)得到首位数进行比较

bool isPalindrome(int x) 
{
    if(x<0)//复数返回fasle
        return false;
    int len=1;
    int i=x;    
    //求出来x数字的位数
    while(i/10>0)
    {
        i=i/10;
        len++;
    }
  
    int tem1,tem2; 
    while(x>0)
    {
        tem1=x%10;
        tem2=x/pow(10,(double)len-1);//10的n次方,函数pow(double x,double y)
        if(tem1!=tem2)
            return false;
        else
        {   
            x=x-tem1*pow(10,(double)len-1);
            x=x/10;
            len=len-2;
        }
    }
    return true;
}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值