Java实现LeetCode_0012_IntegerToRoman

package javaLeetCode.primary;

import java.util.Scanner;

public class IntegerToRoman_12 {
	public static void main(String[] args) {
		System.out.println("Please input a  integer:");
		@SuppressWarnings("resource")
		Scanner input = new Scanner(System.in);
		int num = input.nextInt();
		System.out.println(intToRoman_2(num));
	}// end main()
	
	/*
	 * Test Data: 
	 * III--3 
	 * IV--4 
	 * IX--9 
	 * LVIII--58 
	 * MCMXCIV--1994
	 * MCCCXIV--1314
	 * MMMIX--3009
	 * MMMCCXLIX--3249
	 */
public static String intToRoman_1(int num) {
        String []roman = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","III","II","I"};
        int []integer = {1000,900,500,400,100,90,50,40,10,9,5,4,3,2,1};
        String str="";
        for(;num>0;) {
        	for(int i=0;i<15;i++) {
        		if(num>=integer[i]) {
        			num -= integer[i];
        			str += roman[i];
        			break;
        		}else {
        			continue;
        		}//end if
        	}//end for
        }//end for
	return str;
    }//end intToRoman()

/**
 * Use the simplest method.
 * */
public static String intToRoman_2(int num) {
	
    String str="";
    int a = num/1000;
    int b = num%1000/100;
    int c = num%100/10;
    int d = num%10;

    //Enumerate each possible value
    if(a==0) {str+="";}
    if(a==1) {str+="M";}
    if(a==2) {str+="MM";}
    if(a==3) {str+="MMM";}
    
    if(b==0) {str+="";}
    if(b==1) {str+="C";}
    if(b==2) {str+="CC";}
    if(b==3) {str+="CCC";}
    if(b==4) {str+="CD";}
    if(b==5) {str+="D";}
    if(b==6) {str+="DC";}
    if(b==7) {str+="DCC";}
    if(b==8) {str+="DCCC";}
    if(b==9) {str+="CM";}
    
    if(c==0) {str+="";}
    if(c==1) {str+="X";}
    if(c==2) {str+="XX";}
    if(c==3) {str+="XXX";}
    if(c==4) {str+="XL";}
    if(c==5) {str+="L";}
    if(c==6) {str+="LX";}
    if(c==7) {str+="LXX";}
    if(c==8) {str+="LXXX";}
    if(c==9) {str+="XC";}
    
    if(d==0) {str+="";}
    if(d==1) {str+="I";}
    if(d==2) {str+="II";}
    if(d==3) {str+="III";}
    if(d==4) {str+="IV";}
    if(d==5) {str+="V";}
    if(d==6) {str+="VI";}
    if(d==7) {str+="VII";}
    if(d==8) {str+="VIII";}
    if(d==9) {str+="IX";}
    
    return str;
}//end intToRoman()
}//end IntegerToRoman_12


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值