Monday, September 2, 2013

Integer to Romans conversion

Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.

string intToRoman(int num) {
 string romans[] =  {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C",  "CD",  "D",   "CM",      "M" };
  int ints[] =       {1,    4,    5,   9,   10,   40,  50,  90, 100,    400,   500,  900,      1000 };
  int i  = sizeof(ints)/ sizeof(ints[0]) - 1;
  string result = "";
  while(i >= 0)
  {
  if(num > 0 )
  {
   if(ints[i] > num)
   {
    i--;
   }
   else
   {
    num = num - ints[i];
    result =   result + romans[i] ; 
   }
  }
  else
  {
   break;
  }
  }

  return result;
}

No comments:

Post a Comment