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

Leetcode:Integer to Roman

时间:2017-06-18 13:19:41      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:空间复杂度   https   空间   epo   ring   pre   res   转换   tor   

问题大意是将整数(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 = valueRepresented[onePos];
16             int value = (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 == 9) {
31                     s.append(signatures[onePos]);
32                 }
33                 s.append(signatures[tenPos]);
34             }
35         }
36         return s.toString();
37     }
38 }

 

Leetcode:Integer to Roman

标签:空间复杂度   https   空间   epo   ring   pre   res   转换   tor   

原文地址:http://www.cnblogs.com/dalt/p/7043976.html

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