Integer to Roman

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

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

 

我的想法把:

首先呢取出数字中的每一个数,转化为罗马数字

 1     public String intToRoman(int num) {
 2         int i = 0;
 3         String s = "";
 4         while(num>0) {
 5             //取出num里面的数字
 6             s = charge_Roman(num%10,i++) + s;
 7             num = num/10;
 8         }
 9         return s;
10     }
11     public String charge_Roman(int num,int i) {
12         String[] Symbol = {"I","V","X","L","C","D","M"};
13         String s = "";
14         while(num > 0) {
15             //判断num是否大于5
16             if(num >= 5) {
17                 //判断num是否是9
18                 if(num == 9) {
19                     s+=Symbol[i*2]+Symbol[i*2+2];//是9就取出数组相应的数字
20                     num-=9;//num归0
21                 }
22                 else {
23                     s+=Symbol[i*2+1];//不是就取出5 num减去5
24                     num-=5;
25                 }
26             }
27             else {
28                 if(num == 4) {
29                     s+=Symbol[i*2]+Symbol[i*2+1];//是4就取出数组相应的数字
30                     num-=4;//num归0
31                 }
32                 else {
33                     s+=Symbol[i*2];//不是就取出1
34                     num-=1;//num-1
35                 }
36             }
37         }
38         return s;
39     }

嗯,我认为,还算科学的做法。。。

结果吧,前面的人

 1 class Solution {
 2     public String intToRoman(int num) {
 3         StringBuilder result = new StringBuilder();
 4         
 5         int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
 6         String[] strs = {"M", "CM", "D", "CD", "C", "XC","L","XL","X","IX","V","IV","I"};
 7 
 8         for (int i = 0; i < values.length; i++) {
 9             while (num >= values[i]) {
10                 num -= values[i];
11                 result.append(strs[i]);
12             }
13         }
14         
15         return result.toString();
16     }
17 }

嗯,赢了。

posted @ 2018-09-06 18:58  dafeifeifei  阅读(70)  评论(0编辑  收藏  举报