leetcode 9. Palindrome Number

本文介绍了一种不使用额外空间判断整数是否为回文数的方法。提供了两种实现方式:一种是通过直接比较整数的首尾数字,另一种是将整数转为字符串后进行比较。附带给出了C++代码示例。

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

9. Palindrome Number

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


way-1: force, 强行每次把首位两个数字提出来比较。


way-2:int to string


class Solution {
public:
    string itos(int i) // 将int 转换成string,这个函数可以将任何类型转换为string
    {   
        stringstream s;
        s << i;
        return s.str();
    }
    
    bool isPalindrome(int x) 
    {   
        //way-1
        int xx = x;
        if (x < 0)
            return false;
        int k = 1;
        while(xx / 10 != 0)
        {
            xx = xx / 10;
            k++;
        }

        int x1,x2;
        for(int i=0;i<k/2;i++)
        {   
            xx = x;
            for(int j=0;j<i;j++)
                xx = xx / 10;
            x1 = xx % 10;
            
            xx = x;
            
            for(int j=0;j<k-i-1;j++)
                xx = xx/10;
            x2 = xx % 10;
            
            if(x1 != x2)
                return false;
        }
        return true;
        
        
        //way-2
        /*
        string s1 = itos(x);
        string s2 = s1;
        reverse(s2.begin(), s2.end());
        return s1 == s2;
        */
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值