【leetcode】数字转罗马数字

最近刷了很多leetcode, 无聊的题目就不写了,写点有意思的,比如这道阿拉伯数字转罗马数字。

题目给了几个例子,具体来说就是每一位的49和其他不一样,其他都是累加。

那么根据每一位的不同,我们按位计算,代码虽然多了一点,但是能解决问题。每一位最多判断四次。

package com.Int_to_Roman;
import java.util.Collections;

public class Solution {
	
	public String Ge(int num) {
		if (num<4)
			return String.join("", Collections.nCopies(num, "I"));
		else if (num == 4)
			return "IV";
		else if (num == 9)
			return "IV";
		else
			return "V"+String.join("", Collections.nCopies(num-5, "I"));
	}
	public String Shi(int num) {
		if (num<4)
			return String.join("", Collections.nCopies(num, "X"));
		else if (num == 4)
			return "XL";
		else if (num == 9)
			return "XC";
		else
			return "L"+String.join("", Collections.nCopies(num-5, "X"));
	}
	public String Bai(int num) {
		if (num<4)
			return String.join("", Collections.nCopies(num, "C"));
		else if (num == 4)
			return "CD";
		else if (num == 9)
			return "CM";
		else
			return "D"+String.join("", Collections.nCopies(num-5, "C"));
	}
	public String Qian(int num) {
		return String.join("", Collections.nCopies(num, "M"));
	}
	
	public String intToRoman(int num) {
		String res = "";
		int count = 0;
		while(num !=0) {
			int mod = num%10;
			num = num/10;	
			if (count==0)
				res = Ge(mod)+res;
			else if (count == 1)
				res = Shi(mod)+res;
			else if (count == 2)
				res = Bai(mod)+res;
			else
				res = Qian(mod)+res;
			count+=1;
		}
        return res;
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Solution s = new Solution();
		System.out.println(s.intToRoman(1994));
	}

}

提交虽然成功了,但是看到有位大神写得更加简单的方法,就是每次从大到小,减去相应的数字,再添加上这些数字对应的罗马数字。简单到没朋友,佩服佩服,而我就只会用这种近乎蠢的办法。还是要学习一下。

public class Solution {
public String intToRoman(int num) {

    int[] values = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
    String[] strs = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
    
    StringBuilder sb = new StringBuilder();
    
    for(int i=0;i<values.length;i++) {
        while(num >= values[i]) {
            num -= values[i];
            sb.append(strs[i]);
        }
    }
    return sb.toString();
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值