Problem:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Analysis:
In roman number system, there are 3 special cases
1. 900 or 400
2. 90 or 40
3. 9 or 4
Process the integer number digit by digit, if it's 9 or 4, process it separately. Then if it's 5~8 or it's 0~3, need diferent process.
Code:

1 class Solution { 2 public: 3 string intToRoman(int num) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 7 // Roman digit: I:1, V:5, X:10, L:50, C:100, D:500, M:1000 8 // Special Case: 4:IV, 9:IX, 40:XL, 90:XC, 400:CD, 900:CM 9 10 int rom[7] = {1000, 500, 100, 50, 10, 5, 1}; 11 char romc[7] = {'M', 'D', 'C', 'L', 'X', 'V', 'I'}; 12 char tmp[20]; 13 int idx = 0; 14 15 for (int t = 1000, pt=-1; t > 0; t /= 10, pt+=2) { 16 int digit = num / t; 17 18 switch(digit) { 19 case 9: 20 tmp[idx++] = romc[pt+1]; 21 tmp[idx++] = romc[pt-1]; 22 break; 23 case 8: case 7: case 6: case 5: 24 tmp[idx++] = romc[pt]; //5 25 for (int i=0; i<digit-5; i++) { 26 tmp[idx++] = romc[pt+1]; 27 } 28 break; 29 case 4: 30 tmp[idx++] = romc[pt+1]; 31 tmp[idx++] = romc[pt]; 32 break; 33 case 3: case 2: case 1: 34 for (int i=0; i<digit; i++) { 35 tmp[idx++] = romc[pt+1]; 36 } 37 break; 38 case 0: default: break; 39 } 40 num %= t; 41 } 42 43 tmp[idx] = '\0'; 44 string res(tmp); 45 return res; 46 } 47 };
Attention: