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;
    }
};

小结

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

猜你喜欢

转载自www.cnblogs.com/multhree/p/10327994.html