Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
熟悉罗马数字和阿拉伯数字的转换规则,并找出规律。写出程序。 此题重点在提出规律。
阿拉伯数字到罗马数字的映射可以参考http://baike.baidu.com/view/42061.htm?fr=aladdin
string toRoman(string Roman, int size, int num) //C++ { string tmp = ""; if(num == 0) return tmp; int tmpnum = num; int tmpsize = size; while(tmpsize > 1) { tmpnum = tmpnum/10; tmpsize--; } int topnum = tmpnum; if(tmpnum <4) { while(tmpnum>0) { tmp += Roman.substr((size-1)*2,1); tmpnum--; } } else if(tmpnum > 8) { tmp += Roman.substr((size-1)*2,1); tmp +=Roman.substr((size-1)*2+2,1); } else { if(tmpnum ==4 ) { tmp += Roman.substr((size-1)*2,1); tmp += Roman.substr((size-1)*2+1,1); } else { tmp += Roman.substr((size-1)*2+1,1); tmpnum = tmpnum-5; while(tmpnum>0) { tmp += Roman.substr((size-1)*2,1); tmpnum--; } } } tmpsize =size; while(tmpsize >1) { topnum *= 10; tmpsize--; } tmp += toRoman(Roman,size-1,num-topnum); return tmp; } string intToRoman(int num) { string Roman = "IVXLCDM"; int size = 0; int temp = num; while(temp >0) { size++; temp = temp/10; } string result = toRoman(Roman,size,num); return result; }
原文地址:http://blog.csdn.net/chenlei0630/article/details/41728715