Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
逐区间做处理。
解法一:非递归
class Solution { public: string intToRoman(int num) { string ret; //M<-->1000 while(num >= 1000) { ret += ‘M‘; num -= 1000; } //to here, num < 1000 //CM<-->900 if(num >= 900) { ret += "CM"; num -= 900; } //to here, num < 900 //D<-->500 if(num >= 500) { ret += ‘D‘; num -= 500; } //to here, num < 500 if(num >= 400) { ret += "CD"; num -= 400; } //to here, num < 400 //C<-->100 while(num >= 100) { ret += ‘C‘; num -= 100; } //to here, num < 100 //XC<-->90 if(num >= 90) { ret += "XC"; num -= 90; } //to here, num < 90 //L<-->50 if(num >= 50) { ret += ‘L‘; num -= 50; } //to here, num < 50 //XL<-->40 if(num >= 40) { ret += "XL"; num -= 40; } //to here, num < 40 //X<-->10 while(num >= 10) { ret += ‘X‘; num -= 10; } //to here, num < 10 //IX<-->9 if(num >= 9) { ret += "IX"; num -= 9; } //to here, num < 9 //V<-->5 if(num >= 5) { ret += ‘V‘; num -= 5; } //to here, num < 5 //IV<-->4 if(num >= 4) { ret += "IV"; num -= 4; } //to here, num < 4 //I<-->1 while(num >= 1) { ret += ‘I‘; num -= 1; } return ret; } };
解法二:递归
class Solution { public: string intToRoman(int num) { if(num>=1000) return "M"+intToRoman(num-1000); else if(num>=900) return "CM"+intToRoman(num-900); else if(num>=500) return "D"+intToRoman(num-500); else if(num>=400) return "CD"+intToRoman(num-400); else if(num>=100) return "C"+intToRoman(num-100); else if(num>=90) return "XC"+intToRoman(num-90); else if(num>=50) return "L"+intToRoman(num-50); else if(num>=40) return "XL"+intToRoman(num-40); else if(num>=10) return "X"+intToRoman(num-10); else if(num>=9) return "IX"+intToRoman(num-9); else if(num>=5) return "V"+intToRoman(num-5); else if(num>=4) return "IV"+intToRoman(num-4); else if(num>=1) return "I"+intToRoman(num-1); else return ""; } };
时间: 2024-10-02 17:35:42