Integer to Roman - LeetCode

题目链接

Integer to Roman - LeetCode

注意点

  • 考虑输入为0的情况

解法

解法一:从大到小考虑1000,900,500,400,100,90,50,40,10,9,5,4,1这些数字,大于就减去,直到为0。时间复杂度为O(n)

class Solution {
public:
    string intToRoman(int num) {
        string ans = "";
        while(num > 0)
        {
            if(num >= 1000)
            {
                ans += "M";
                num -= 1000;
            }
            else if(num >= 900)
            {
                ans += "CM";
                num -= 900;
            }
            else if(num >= 500)
            {
                ans += "D";
                num -= 500;
            }
            else if(num >= 400)
            {
                ans += "CD";
                num -= 400;
            }
            else if(num >= 100)
            {
                ans += "C";
                num -= 100;
            }
            else if(num >= 90)
            {
                ans += "XC";
                num -= 90;
            }
            else if(num >= 50)
            {
                ans += "L";
                num -= 50;
            }
            else if(num >= 40)
            {
                ans += "XL";
                num -= 40;
            }
            else if(num >= 10)
            {
                ans += "X";
                num -= 10;
            }
            else if(num >= 9)
            {
                ans += "IX";
                num -= 9;
            }
            else if(num >= 5)
            {
                ans += "V";
                num -= 5;
            }
            else if(num >= 4)
            {
                ans += "IV";
                num -= 4;
            }
            else if(num >= 1)
            {
                ans += "I";
                num -= 1;
            }
        }
        return ans;
    }
};

874b0eb1gy1fzlg8myq9qj216o0kdgmq.jpg

小结

  • 终于有一次击败100%了!!不过这题难度为什么会是中等啊...

转载于:https://www.cnblogs.com/multhree/p/10327994.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值