Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
<Solution>這題不難,只是要先搞清楚羅馬數字 (參考資料)
Symbol | I | V | X | L | C | D | M |
---|---|---|---|---|---|---|---|
Value | 1 | 5 | 10 | 50 | 100 | 500 | 1,000 |
Number | 4 | 9 | 40 | 90 | 400 | 900 |
---|---|---|---|---|---|---|
Notation | IV | IX | XL | XC | CD | CM |
1934 = MCMXXXIV = 1000 + 900 + 30 + 4
234 = CCXXXIV = 200 + 30 + 4
19 = XIX = 10 + 9
5 = V
從上面的例子可以知道,能找出幾個斷點,把羅馬數字分成幾類
- 斷點 : 1、4、5、9、10、40、50、90、100、400、500、900、1000
- 羅馬數字 : I、IV、V、X、XL、L、XC、C、CD、D、CM、M
例如 95,在 90 - 100之間,先由一個 90 組成,是 XC;然後減去 90 剩五
剛好是斷點5,所以是 V,最後 95 = XCV
寫成code 如下
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
string intToRoman(int num) { | |
string ans = ""; | |
int val[13] = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; | |
string rom[13] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; | |
for(int i = 0; i < 13; i++) { | |
while(num >= val[i]) { | |
num -= val[i]; | |
ans += rom[i]; | |
} | |
if(num == 0) { | |
break; | |
} | |
} | |
return ans; | |
} | |
}; |
沒有留言:
張貼留言