1. 程式人生 > >【LeetCode】012. Integer to Roman

【LeetCode】012. Integer to Roman

rom pan lee style roman post 連續 ive res

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

題解:

  觀察 1 到 10 :Ⅰ,Ⅱ,Ⅲ,Ⅳ(IIII),Ⅴ,Ⅵ,Ⅶ,Ⅷ,Ⅸ,Ⅹ,Ⅺ

  難點在於出現字符不能連續超過三次,以及大數左邊至多有一個小數。所以要分情況:1 - 3,4,5 - 8,9。將小數在大數左邊的情況摘出來。

Solution 1

  貪心策略

 1 class Solution {
 2 public:
 3     string intToRoman(int
num) { 4 string res = ""; 5 vector<int> weights{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 6 vector<string> tokens{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 7 8 int i = 0; 9 while (num && i < weights.size()) {
10 while (num >= weights[i]) { 11 num -= weights[i]; 12 res += tokens[i]; 13 } 14 ++i; 15 } 16 17 return res; 18 } 19 };

Solution 2

 1 class Solution {
 2 public:
 3     string intToRoman(int num) {
4 vector<string> M = { "", "M", "MM", "MMM" }; 5 vector<string> C = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }; 6 vector<string> X = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }; 7 vector<string> I = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }; 8 return M[num / 1000] + C[(num % 1000) / 100] + X[(num % 100) / 10] + I[num % 10]; 9 } 10 };

【LeetCode】012. Integer to Roman