首页 > 代码库 > Leetcode:Integer to Roman

Leetcode:Integer to Roman

问题大意是将整数(1~3999)转换为罗马数字形式,并以字符串的形式返回。至于罗马数字可以参考https://en.wikipedia.org/wiki/Roman_numerals中的说法。


很暴力的解决方案,直接看代码吧,时间复杂度和空间复杂度均为常数,即O(1)。


代码的运行时间是82ms

 1 package cn.dalt.leetcode;
 2 
 3 /**
 4  * Created by dalt on 2017/6/18.
 5  */
 6 public class IntegertoRoman {
 7     public String intToRoman(int num) {
 8         StringBuilder s = new StringBuilder();
 9         char[] signatures = new char[]{‘I‘, ‘V‘, ‘X‘, ‘L‘, ‘C‘, ‘D‘, ‘M‘, ‘ ‘, ‘ ‘};
10         int[] valueRepresented = new int[]{1, 5, 10, 50, 100, 500, 1000, 5000, 10000};
11         for (int i = signatures.length - 1; i >= 0; i -= 2) {
12             int tenPos = i;
13             int fivePos = i - 1;
14             int onePos = i - 2;
15             int oneValue =http://www.mamicode.com/ valueRepresented[onePos];
16             int value = http://www.mamicode.com/(num / oneValue) % 10;
17             if (value <= 3) {
18                 for (int j = 0; j < value; j++) {
19                     s.append(signatures[onePos]);
20                 }
21             } else if (value <= 8) {
22                 for (int j = 4; j >= value; j--) {
23                     s.append(signatures[onePos]);
24                 }
25                 s.append(signatures[fivePos]);
26                 for (int j = 5; j < value; j++) {
27                     s.append(signatures[onePos]);
28                 }
29             } else {
30                 if (value =http://www.mamicode.com/= 9) {
31                     s.append(signatures[onePos]);
32                 }
33                 s.append(signatures[tenPos]);
34             }
35         }
36         return s.toString();
37     }
38 }

 

Leetcode:Integer to Roman