码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Integer to Roman

时间:2015-02-24 13:47:56      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

Given an integer, convert it to a roman numeral.

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

对于这道题,要把罗马数字中的几个特殊的数字保存到一张表中,如,4,5,9,10等,然后开始遍历拼接

 1 package Integer.to.Roman;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 
 7 public class IntegerToRoman {
 8     List<Node> list=new ArrayList<Node>();
 9     class Node{
10         int key;
11         String value;
12         public Node(int key,String value){
13             this.key=key;
14             this.value=value;
15         }    
16     }
17     public void add(int key,String value){
18         Node node=new Node(key,value);
19         list.add(node);
20     }
21     public int listSize(){
22         return list.size();
23     }
24      public String intToRoman(int num) {
25         this.add(1000, "M");
26         this.add(900,  "CM");
27         this.add(500,  "D");
28         this.add(400,  "CD");
29         this.add(100,  "C");
30         this.add(90,   "XC");
31         this.add(50,   "L");
32         this.add(40,   "XL");
33         this.add(10,   "X");
34         this.add(9,    "IX");
35         this.add(5,    "V");
36         this.add(4,    "IV");
37         this.add(1,    "I");
38         StringBuilder res = new StringBuilder();
39         int i=0;
40         while(num>0){
41             int key=list.get(i).key;
42             String value=list.get(i).value;
43             if(num/key==0)
44             {
45                 i++;
46                 continue;
47             }
48             for(int j=0;j<num/key;j++){
49                 res.append(value);
50             }
51             num=num%key;
52         }
53         return res.toString();
54             
55         }
56      public static void main(String args[]){
57          IntegerToRoman service=new IntegerToRoman();
58          int num=12;
59         String s= service.intToRoman(num);
60         System.out.println(s);
61      }
62 }

 

Leetcode Integer to Roman

标签:

原文地址:http://www.cnblogs.com/criseRabbit/p/4298606.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!