本文主要是介绍Int to Roman,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
阿拉伯数字转罗马数字(1~3999)
思路:
直接从个位数开始转起,分别用10,100,1000,10000取余数,不同的余数采用不同的解决办法,最后返回字符串
代码
class Solution {
public:string intToRoman(int num)
{int d = 10;int n = num;string rslt("");while (n > 0){//给10取余数int single = n % 10;switch (single){case 0:break;case 4:rslt += "IV" ; break;case 5:rslt += "V" ; break; case 1: case 2:case 3:{int tmp = single;while (tmp > 0){rslt += "I";--tmp;}break; }case 6:case 7: case 8:{int tmp = single;rslt += "V";while (tmp > 5){rslt += "I";--tmp;}break;}case 9:rslt += "IX"; break;}//减去n = n - single;if (n == 0)return rslt;//给100取余数int decade = n % 100;switch (decade){case 40:rslt = "XL"+rslt; break;case 50:rslt = "L" + rslt; break;case 0:break;case 10: case 20:case 30:{int tmp = decade;while (tmp >= 10){rslt = "X" + rslt;tmp -= 10;}break;}case 60:case 70: case 80:{int tmp = decade;string tmpRslt = "L";while (tmp > 50){tmpRslt += "X";tmp -= 10;}rslt = tmpRslt + rslt;break;}case 90:{rslt = "XC" + rslt;break;}}//减去n = n - decade;if (n == 0)return rslt;//给1000取余数int hunderd = n % 1000;switch (hunderd){case 0:break;case 400:rslt = "CD" + rslt; break;case 500:rslt = "D" +rslt; break;case 100: case 200:case 300:{int tmp = hunderd;while (tmp >= 100){rslt = "C" + rslt;tmp -= 100;}break;}case 600:case 700: case 800:{int tmp = hunderd;string tmpRslt = "D";while (tmp > 500){tmpRslt += "C";tmp-=100;}rslt = tmpRslt + rslt;break;}case 900: {rslt = "CM" + rslt;break;}}//减去n = n - hunderd;if (n == 0)return rslt;//给10000取余数int thousand = n % 10000;switch (thousand){case 1000:rslt = "M" + rslt; break;case 2000:rslt = "MM" + rslt; break;case 3000:rslt = "MMM" + rslt; break;}n = n - thousand;}return rslt;}
};
这篇关于Int to Roman的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!