LeetCode12 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. 相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3;
  2. 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12;
  3. 小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9

所以打表存一下数字和罗马字母的对应关系,从千位开始向下处理即可。

代码:

 1 class Solution {
 2 public:
 3     string intToRoman(int num) {
 4         string flag[4][10] = {
 5                          {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
 6                          {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
 7                          {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
 8                          {"", "M", "MM", "MMM"}
 9                         };
10         string result;
11         int mod1 = 1000;
12         int sum = 3;
13         while (mod1 != 0) {
14             int temp = num / mod1;
15             result += flag[sum][temp];
16             num -= temp * mod1;
17             sum--;
18             mod1 /= 10;
19         }
20         return result;
21     }
22 };

 

posted @ 2016-08-08 21:56  wangxiaobao1114  阅读(178)  评论(0编辑  收藏  举报