Leetcode-Integer to Roman

LiBlog發表於2014-11-26

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

Solution:

 1 public class Solution {
 2     public String intToRoman(int num) {
 3         String[] symbol = new String[]{"I","V","X","L","C","D","M"};
 4         int[] val = new int[]{1,5,10,50,100,500,1000};
 5         
 6         String res = "";
 7         int index = 6;
 8         int symNum = num/val[index];
 9         int left = num%val[index];
10         if (symNum>0)
11             for (int i=0;i<symNum;i++) res += symbol[index];
12         index -=2;
13         while (left!=0){
14             symNum = left/val[index];
15             left = left%val[index];            
16             if (symNum==0){
17                index-=2;
18                continue;             
19             } else if (symNum==9) res += symbol[index]+symbol[index+2];
20             else if (symNum==4) res += symbol[index]+symbol[index+1];
21             else if (symNum<4) 
22                 for (int i=0;i<symNum;i++) res += symbol[index];
23             else {
24                 res += symbol[index+1];
25                 for (int i=0;i<symNum-5;i++) res += symbol[index];
26             }
27             index -= 2;
28 
29         }
30 
31         return res;
32     }
33 }