[LeetCode 9,13][简单]回文数/罗马数字转整数

本文深入解析了两道经典C++算法题:判断一个整数是否为回文数,以及将罗马数字转换为整数。通过代码示例详细讲解了算法的设计思路和实现细节。

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

9.回文数
题目链接

class Solution {
public:
    typedef long long LL;
    bool isPalindrome(int x) {
        LL x1=abs((LL)x),x2=0;
        while(x1){
            x2*=10;
            x2+=(x1%10);
            x1/=10;
        }
        if(x2==x)return true;
        else return false;
    }
};

13.罗马数字转整数
题目链接

class Solution {
public:
    char Seq[8]="IVXLCDM";
    int ind[8]={1,5,10,50,100,500,1000,-1};
    int sind[27];
    void init(){
        for(int i=0;i<7;i++){
            sind[Seq[i]-'A']=i;
        }
    }
    char str[100];
    int romanToInt(string s) {
        init();
        strcpy(str,s.c_str());
        int l=s.size(),ans=0;
        for(int i=0;i<l;i++){
            int f=1;
            if(i!=(l-1)){
                if(sind[str[i]-'A']<sind[str[i+1]-'A'])f=-1;
            }
            ans+=(f*ind[sind[str[i]-'A']]);
        } 
        return ans; 
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值