標籤:leetcode 羅馬數字 轉換
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
class Solution {public: string intToRoman(int num) { char symbol[] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'}; int i = 6; int weight = 1000; string result; while (num) { const int digit = num / weight; if (digit <= 3) { result.append(digit, symbol[i]); } else if (digit == 4) { result.append(1, symbol[i]); result.append(1, symbol[i+1]); } else if (digit == 5) { result.append(1, symbol[i+1]); } else if (digit <= 8) { result.append(1, symbol[i+1]); result.append(digit-5, symbol[i]); } else { result.append(1, symbol[i]); result.append(1, symbol[i+2]); } num %= weight; weight /= 10; i -= 2; } return result; }};
此題的關鍵是對羅馬數字規則的理解。
羅馬數字雖然有七個基底字元,但我覺得對規則的理解可以從I和V兩個字元開始。
I表示1,V表示5.
如何表示阿拉伯數字1-9呢?
1~3, 可以用I來湊數。如I,II, III
4呢,那就5-1, IV (左邊的數字較小則為減)。
5,就是 V
6~8,則用5+, 即先用一個V,不夠的用I來湊數, 如VI, VII, VIII。
9的話,10-1,10就得依靠下一組羅馬數字幫忙了。
下一組就是 10,50,
再下一組就是 100, 500,
但組數規則和I V是一樣的,只是符號不一樣,代表的權重不一樣。
IV負責個位元
XL負責十位元
CD負責百位元
MV負責千位元
XL負責萬位元
CD負責十萬位元
...
此題目考到3999為止,大概是因為從4000開始,就得用到帶上劃線的字元了。
Integer to Roman -- leetcode