题目描述:

Given an integer, convert it to a roman numeral.

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

解题思路:

观察罗马数字可以发现个十百千位上的数字是可以分开考虑的。

罗马字符    I   V   X   L   C   D   M
整数数字    1   5   10  50  100 500 1000

而每位上的情况可以分成这五种:

  1. 如果该位数字是9,则说明是上面3、4、5这三种情况中的一种,即把I、X、C中的一个放到了大数字的左侧;
  2. 如果该位数字是5~8,则说明是上面1这种情况,即I、X、C中的一个,自身连用或者放在大数的右边连用;
  3. 如果该位数字是4,则说明同样是上面3、4、5这三种情况中的一种,即把I、X、C中的一个放到了大数字的左侧;
  4. 如果该位数字是0~3,则同样说明是上面1这种情况,即I、X、C中的一个,自身连用或者放在大数的右边连用。

代码:

 1 class Solution {
 2 public:
 3     string intToRoman(int num) {
 4         int n[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4 ,1};
 5         string str[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
 6         string result = "";
 7         for(int i = 0; num > 0; i++){
 8             for(int j = num/n[i]; j > 0; j--)
 9                 result+=str[i];
10             num%=n[i];
11         }
12         return result;
13     }
14 };

 

 

 

posted on 2018-02-23 21:53  宵夜在哪  阅读(102)  评论(0编辑  收藏  举报