## Saturday, December 22, 2012

### [LeetCode] Integer to Roman 解题报告

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

[解题思路]

1<=digit <=3
digit =4
digit = 5
5<digit<=8
digit =9

[Code]

``````1:  string intToRoman(int num) {
2:      // Start typing your C/C++ solution below
3:      // DO NOT write int main() function
4:      char symbol[7] = { 'I','V','X', 'L','C', 'D','M'};
5:      string roman;
6:      int scale = 1000;
7:      for(int i =6; i>=0; i-=2)
8:      {
9:        int digit = num/scale;
10:        if(digit != 0)
11:        {
12:          if(digit <= 3)
13:          {
14:            roman.append(digit, symbol[i]);
15:          }
16:          else if(digit ==4)
17:          {
18:            roman.append(1, symbol[i]);
19:            roman.append(1, symbol[i+1]);
20:          }
21:          else if(digit ==5)
22:          {
23:            roman.append(1, symbol[i+1]);
24:          }
25:          else if(digit <=8)
26:          {
27:            roman.append(1, symbol[i+1]);
28:            roman.append(digit-5, symbol[i]);
29:          }
30:          else if(digit ==9)
31:          {
32:            roman.append(1, symbol[i]);
33:            roman.append(1, symbol[i+2]);
34:          }
35:        }
36:        num = num%scale;
37:        scale/=10;
38:      }
39:      return roman;
40:    }
``````