sourcecode

Friday, November 30, 2012

Integer to Roman

http://www.leetcode.com/onlinejudge
http://en.wikipedia.org/wiki/Roman_numerals


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



/*Passed both small and large tests**/
class Solution { string buildDigit(string ivx, int num){//num [0~9] string result(""); if (!num) return result;//0 else if (num <= 3){//1,2,3 for(;num>0;--num){ result.push_back(ivx[0]); } } else if (num == 4 || num == 9){//4,9 result.push_back(ivx[0]); result.push_back(ivx[num/4]);//1,or 2 } else{//5,6,7,8 result.push_back(ivx[1]); for(; num > 5; --num){ result.push_back(ivx[0]); } } return result; } public: string intToRoman(int num) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<string> one(3,""); one[0]="IVX"; one[1]="XLC"; one[2]="CDM"; string result(""); for(int ii = 0; ii < 3 && num>0; ++ii){ int digit = num%10; num /= 10; result = buildDigit(one[ii], digit)+result; } for(;num>0;--num){ result = one[2][2] + result; } return result; } };

No comments: