【leetcode】Integer to Roman
5040 ワード
Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
欲張りアルゴリズムを利用する
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
, ;(1) Ⅰ、X 、C , , , ; 。(2) V 、L 、D ; , 。(3)V X Ⅰ。(4)L C ×。(5)D M C
欲張りアルゴリズムを利用する
1 class Solution {
2 public:
3 string intToRoman(int num) {
4
5 string result="";
6 string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
7 int value[]= {1000,900,500,400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
8
9 int i=0;
10 while(num!=0)
11 {
12 while(num>=value[i])
13 {
14 num=num-value[i];
15 result+=symbol[i];
16 }
17 i++;
18 }
19 return result;
20 }
21 };