Thursday, June 5, 2014

Leetcode: Integer to Roman

Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.

Solution:

public class Solution {
    public String intToRoman(int num) {
        StringBuilder sb = new StringBuilder();
        add(sb, num/1000, ' ', ' ', 'M');
        add(sb, (num/100)%10, 'M', 'D', 'C');
        add(sb, (num/10)%10, 'C', 'L', 'X');
        add(sb, num%10, 'X', 'V', 'I');
        return sb.toString();
        
    }
    
    public void add(StringBuilder sb, int num, char tenElement, char fiveElement, char oneElement)
    {
        if (num>8)
        {
            for(int i=10; i>num; i--)
                sb.append(oneElement);
            sb.append(tenElement);
        }
        else if(num>=5)
        {
            sb.append(fiveElement);
            for(int i=5; i<num; i++)
                sb.append(oneElement);
        }
        else if(num>3)
        {
            for(int i=5; i>num; i--)
                sb.append(oneElement);
            sb.append(fiveElement);
        }
        else
        {
            for(int i=0; i<num; i++)
                sb.append(oneElement);
        }
    }
}

No comments :

Post a Comment