Skip to content

Latest commit

 

History

History
59 lines (49 loc) · 1.04 KB

12. Integer to Roman.md

File metadata and controls

59 lines (49 loc) · 1.04 KB

12. Integer to Roman

Problem

Given an integer, convert it to a roman numeral.

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

tag:

Solution

java

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

go

func intToRoman(num int) string {
	var roman bytes.Buffer
	i := 0
	for num > 0 {
		k := num / values[i]
		for j := 0; j < k; j++ {
			roman.WriteString(symbols[i])
			num -= values[i]
		}
		i++
	}
	return roman.String()
}