Integer to Roman

来源:互联网 发布:sql declare 全局变量 编辑:程序博客网 时间:2024/04/19 22:26

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){      if (num >= 4000) return "";   string res;   for (int i = 1; i <= num / 1000; i++)   res.push_back('M');   num %= 1000;   if (num < 400)   for (int i = 1; i <= num / 100; i++)   res.push_back('C');   else if (num <500)   res += "CD";   else if (num < 900)   {   res.push_back('D');   num -= 500;   for (int i = 1; i <= num / 100; i++)   res.push_back('C');   }   else     res += "CM";   num %= 100;if (num < 40)   for (int i = 1; i <= num / 10; i++)   res.push_back('X');   else if (num <50)   res += "XL";   else if (num < 90)   {   res.push_back('L');   num -= 50;   for (int i = 1; i <= num / 10; i++)   res.push_back('X');   }   else     res += "XC";   num %= 10;if (num < 4)   for (int i = 1; i <= num; i++)   res.push_back('I');   else if (num <5)   res += "IV";   else if (num < 9)   {   res.push_back('V');   num -= 5;   for (int i = 1; i <= num; i++)   res.push_back('I');   }   else     res += "IX";   return res;    }};



简化后的

class Solution{public:void help(int& num, int div, char ch1, char ch2, char ch3, string& res){   if (num < 4 * div)   for (int i = 1; i <= num / div; i++)   res.push_back(ch1);   else if (num <5 * div)   {  res.push_back(ch1); res.push_back(ch2);}   else if (num < 9 * div)   {   res.push_back(ch2);   num -= 5 * div;   for (int i = 1; i <= num / div; i++)   res.push_back(ch1);   }   else   {  res.push_back(ch1); res.push_back(ch3);}}    string intToRoman(int num){      if (num >= 4000) return "";   string res;   for (int i = 1; i <= num / 1000; i++)   res.push_back('M');   num %= 1000;   help(num, 100, 'C', 'D', 'M', res);   num %= 100;   help(num, 10, 'X', 'L', 'C', res);   num %= 10;   help(num, 1, 'I', 'V', 'X', res);   return res;    }};


0 0
原创粉丝点击