[LeetCode] 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,5,10,50,100,500,1000,这几个数字,因此,我们可以从大到小遍历,比如2345,2000>1000,得到一个'M',然后变成1345,同样,再减1000,得到"MM",变成345,依次类推即可。
class Solution { public: string intToRoman(int num) { // Note: The Solution object is instantiated only once and is reused by each test case. int data = num; string str; map<int, pair<int, string> > map_data; map_data.insert(make_pair(0, make_pair(1000, "M"))); map_data.insert(make_pair(1, make_pair(900, "CM"))); map_data.insert(make_pair(2, make_pair(500, "D"))); map_data.insert(make_pair(3, make_pair(400, "CD"))); map_data.insert(make_pair(4, make_pair(100, "C"))); map_data.insert(make_pair(5, make_pair(90, "XC"))); map_data.insert(make_pair(6, make_pair(50, "L"))); map_data.insert(make_pair(7, make_pair(40, "XL"))); map_data.insert(make_pair(8, make_pair(10, "X"))); map_data.insert(make_pair(9, make_pair(9, "IX"))); map_data.insert(make_pair(10, make_pair(5, "V"))); map_data.insert(make_pair(11, make_pair(4, "IV"))); map_data.insert(make_pair(12, make_pair(1, "I"))); pair<int, string> pair_data; while(data) { int i = 0; while(i < 13) { pair_data = map_data[i]; if(data >= pair_data.first) { str += pair_data.second; data -= pair_data.first; break; } i++; } } return str; } };
补充:软件开发 , C++ ,