Problem
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Code
string itor(int i,char one,char five,char ten){ string result; if(i < 4){ for(int j = 0;j < i;++j) result += one; } else if(i == 4){ result += one; result += five; } else if(i < 9){ result += five; for(int j = 0;j < i - 5;++j) result += one; } else{ result += one; result += ten; } return result; } string intToRoman(int num) { // Note: The Solution object is instantiated only once and is reused by each test case. string result; result += itor((num/1000)%10,'M','O','O'); result += itor((num/100)%10,'C','D','M'); result += itor((num/10)%10,'X','L','C'); result += itor(num%10,'I','V','X'); return result; }
No comments:
Post a Comment