Integer to Roman (羅馬數字轉換) 【leetcode】
阿新 • • 發佈:2018-12-24
題目:Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
科普了一下表達方式,理解了就不復雜了。I = 1;
V = 5;
X = 10;
L = 50;
C = 100;
D = 500;
M = 1000;
其中每兩個階段的之間有一個減法的表示,比如900=CM, C寫在M前面表示M-C。
範圍給到3999,感覺情況不多直接打表其實更快,用程式碼判斷表示估計比較繁瑣。
然後就是貪心的做法,每次選擇能表示的最大值,把對應的字串連起來。
class Solution { public: string intToRoman(int num) { string str; string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; int value[]= {1000,900,500,400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; for(int i=0;num!=0;++i) { while(num>=value[i]) { num-=value[i]; str+=symbol[i]; } } return str; } };