leetcode第12题——**Integer to Roman

25 篇文章 0 订阅
25 篇文章 0 订阅

题目

Given an integer, convert it to a roman numeral.

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

思路

题目要求把1-3999的整数转换为罗马数字。只要找出罗马数字各位上的规律,就可以很方便地解出了。个位上的罗马数字(1-9)为'I','II','III','IV','V','VI','VII','VIII','IX'],十位上的罗马数字(1-9)为['X','XX','XXX','XL','L','LX','LXX','LXXX','XC'],百位上的罗马数字(1-9)为['C','CC','CCC','CD','D','DC','DCC','DCCC','CM'],千位上1-3分别为M、MM、MMM。
按照这个规律只需要四个字符串列表即可实现转换。
(PS:个人觉得这是刷LeetCode目前为止最简单的一道题)

代码

Python
class Solution(object):
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        if (num < 1) or (num > 3999):
            return None
        thousand = num / 1000
        hundred = (num / 100)%10
        ten = (num / 10)%10
        one = num%10
        rTh = ['','M','MM','MMM']
        rHun = ['','C','CC','CCC','CD','D','DC','DCC','DCCC','CM']
        rTen = ['','X','XX','XXX','XL','L','LX','LXX','LXXX','XC']
        rOne = ['','I','II','III','IV','V','VI','VII','VIII','IX']
        return rTh[thousand]+rHun[hundred]+rTen[ten]+rOne[one]
Java
public class Solution {
    public String intToRoman(int num) {
        if (num < 1 || num > 3999) return null;
		int thousand = num / 1000;
		int hundred = (num / 100)%10;
		int ten = (num / 10)%10;
		int one = num%10;
		String[] rTh = {"","M","MM","MMM"};
		String[] rHun = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
		String[] rTen = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
		String[] rOne = {"","I","II","III","IV","V","VI","VII","VIII","IX"};
		return rTh[thousand]+rHun[hundred]+rTen[ten]+rOne[one];
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值