Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
解题思路:
数字转罗马字符。并不是非常复杂,罗马字符的表示如维基百科所述http://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97。由于数字不多,可以直接用枚举法表示。代码如下:
class Solution { public: string intToRoman(int num) { string qianwei[]={"", "M", "MM", "MMM"}; string baiwei[]={"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; string shiwei[]={"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; string gewei[] ={"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; string result=""; result += qianwei[num/1000]; //千位 num = num%1000; result += baiwei[num/100]; //百位 num = num%100; result += shiwei[num/10]; //十位 num = num%10; result += gewei[num]; //个位 return result; } };网上看到另一个比较好的解法,比我的解法要简练,代码如下:
class Solution { public: string intToRoman(int num) { string str; string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; int value[]= {1000,900,500,400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; for(int i=0;num!=0;++i) { while(num>=value[i]) { num-=value[i]; str+=symbol[i]; } } return str; } };
原文地址:http://blog.csdn.net/kangrydotnet/article/details/45115429