当前位置:网站首页>leetcode. 12 --- integer to Roman numeral

leetcode. 12 --- integer to Roman numeral

2022-06-24 14:26:00 _ End, broken chord

Integer to Roman number

 Insert picture description here

Answer key : simulation
Use the maximum number each time
An array is stored value, An array storage unit
 Insert picture description here

The code is as follows :

class Solution {
    
public:
    string intToRoman(int num) {
    
        // value 
        int value[] = 
        {
    
            1000,
            900,500,400,100,
            90,50,40,10,
            9,5,4,1
        };
        // Company 
        string company[] = 
        {
    
            "M",
            "CM","D","CD","C",
            "XC","L","XL","X",
            "IX","V","IV","I"
        };
        string res;
        for(int i = 0;i < 13;i++)
        {
    
            while(num >= value[i]){
    
                num -= value[i];
                res +=  company[i];
            }
        }
        return res;
    }
};

Time complexity :O(1)
Spatial complexity :O(1)

原网站

版权声明
本文为[_ End, broken chord]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241245416040.html