首页 > 其他 > 详细

Leetcode-Integer to Roman

时间:2014-11-26 14:03:11      阅读:288      评论:0      收藏:0      [点我收藏+]

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 }

 

Leetcode-Integer to Roman

原文:http://www.cnblogs.com/lishiblog/p/4122900.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!