LeetCode#12 Integer to Roman

Problem Definition:

Given an integer, convert it to a roman numeral.

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

Solution:

1)思路基本上就是这个样子,不过因为输入的整数最大不到4000,所以可以直接把循环给拆了。

 1     # @param {integer} num
 2     # @return {string}
 3     def intToRoman(self, num):
 4         dicIntToRoman={1:'I',5:'V',10:'X',50:'L',100:'C',500:'D',1000:'M'}
 5         dicIntToArr={1:[1],2:[1,1],3:[1,1,1],4:[1,5],5:[5],6:[5,1],7:[5,1,1],8:[5,1,1,1],9:[1,10]}
 6         pz=1000
 7         roman=''
 8         while num!=0:
 9             a=num/pz
10             num=num%pz
11             if a==0:
12                 pz/=10
13                 continue
14             arr=dicIntToArr[a]
15             for c in arr:
16                 roman+=dicIntToRoman[pz*c]
17             pz/=10
18         return roman

 

2)

1 public static String intToRoman(int num) {
2         String M[] = {"", "M", "MM", "MMM"};
3         String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
4         String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
5         String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
6         return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
7     }

 

转载于:https://www.cnblogs.com/acetseng/p/4689043.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值