【LeetCode】012. Integer to Roman

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 };

 

posted @ 2018-03-25 16:51  Vincent丶丶  阅读(155)  评论(0编辑  收藏  举报