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.

Solution

Concise O(1) Solution

public class Solution {
    public String intToRoman(int num) {
        String[] ones = new String[] {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
        String[] tens = new String[] {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
        String[] hundreds = new String[] {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
        String[] thousands = new String[] {"", "M", "MM", "MMM"};
        return thousands[num / 1000] + hundreds[num % 1000 / 100] + tens[num % 100 / 10] + ones[num % 10];

    }
}

Analysis

We get value in each ten bits and then get corresponding roman representation
Just remember how roman numbers are counted
Starts from 1 = I, 5 = V, 10 = X, 50 = L, 100 = C, 500 = D, 1000 = M
For a combined roman number, putting a smaller value left means subtracting
Ex. 4 = IV, 40 = XL, 400 = CD

results matching ""

    No results matching ""