博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Integer to Roman
阅读量:5951 次
发布时间:2019-06-19

本文共 2678 字,大约阅读时间需要 8 分钟。

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是否大于516             if(num >= 5) {17                 //判断num是否是918                 if(num == 9) {19                     s+=Symbol[i*2]+Symbol[i*2+2];//是9就取出数组相应的数字20                     num-=9;//num归021                 }22                 else {23                     s+=Symbol[i*2+1];//不是就取出5 num减去524                     num-=5;25                 }26             }27             else {28                 if(num == 4) {29                     s+=Symbol[i*2]+Symbol[i*2+1];//是4就取出数组相应的数字30                     num-=4;//num归031                 }32                 else {33                     s+=Symbol[i*2];//不是就取出134                     num-=1;//num-135                 }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 }

嗯,赢了。

转载于:https://www.cnblogs.com/smallgrass/p/9600302.html

你可能感兴趣的文章