题目
12. 整数转罗马数字
我的思路
对十进制数字,从高位到低位逐个转换即可?
我的实现
class Solution { public: string intToRoman(int num) { string result; while(num>=1000){ num-=1000; result.push_back('M'); } if(num>=900){ num-=900; result.push_back('C'); result.push_back('M'); }else if(num>=400&&num<500){ num-=400; result.push_back('C'); result.push_back('D'); }else if(num>=500){ result.push_back('D'); num=num-500; } while(num>=100){ num-=100; result.push_back('C'); } if(num>=90){ num-=90; result.push_back('X'); result.push_back('C'); }else if(num>=40&&num<50){ num-=40; result.push_back('X'); result.push_back('L'); }else if(num>=50){ result.push_back('L'); num=num-50; } while(num>=10){ num-=10; result.push_back('X'); } if(num>=9){ num-=9; result.push_back('I'); result.push_back('X'); }else if(num>=4&&num<5){ num-=4; result.push_back('I'); result.push_back('V'); }else if(num>=5){ result.push_back('V'); num=num-5; } while(num>=1){ num-=1; result.push_back('I'); } return result; } }; /* 对十进制数字,从高位到低位逐个转换即可? */
拓展学习
其实可以观察转换规律,更简洁优美。贪心算法
class Solution { public: string intToRoman(int num) { int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; string reps[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; string res; int for (int i = 0; i < 13; i ++ ) //这里不使用图里的count了,一遍一遍来就行了 while(num >= values[i]) { num -= values[i]; res += reps[i]; } return res; } }; 作者:z1m 链接:https://leetcode-cn.com/problems/integer-to-roman/solution/tan-xin-ha-xi-biao-tu-jie-by-ml-zimingmeng/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。