leetcode12. Integer to Roman

本文介绍了一个将整数转换为罗马数字的C++实现方法。通过定义阈值和对应的罗马字符,该算法能正确处理从1到3999之间的整数转换。特别地,文章详细展示了如何处理特殊组合如4和9等。

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

思路:
1.找出I/V/X/L/C/D/M组合规律,进行拼接;
1 4 5 9 10 40 50 90 100 400 500 900 1000.。。。

class Solution {
public:
    string intToRoman(int num) {
        int thresholds[7] = {1,5,10,50,100,500,1000};
        char presents[7] = {'I','V','X','L','C','D','M'};
        string s="";
        int step = 6;
        double tempLeft = 0;
        int temp = 0,pos = 0;
        while(step>=0 && num>=0){
            temp = num / thresholds[step];
            while(temp-->0) s = s + presents[step];
            num %= thresholds[step];
            tempLeft= num*1.0/thresholds[step];
            pos = ((step+1)/2-1)*2;
            if((tempLeft>=0.9 && !(step%2) ) && step>0){
              s=s+presents[pos]+presents[step];
              num -=  0.9*thresholds[step];
              step--;
            }else if(( (tempLeft>=0.8 && (step%2) ) ) && step>0){

              s=s+presents[pos]+presents[step];
              num -=  0.8*thresholds[step];
            }
            step--;

        }

        return  s;

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值