Friday, July 10, 2015

Integer to Roman

Given an integer, convert it to a roman numeral.
The number is guaranteed to be within the range from 1 to 3999.
Have you met this question in a real interview? 
Yes
Example
4 -> IV
12 -> XII
21 -> XXI
99 -> XCIX

Clarification
What is Roman Numeral?
public class Solution {
    /**
     * @param n The integer
     * @return Roman representation
     */
    public String intToRoman(int n) {
        // Write your code here
        String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        int [] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        StringBuffer buffer = new StringBuffer();
        for(int i = 0; i < values.length; i++){
            while(n >= values[i]){
                buffer.append(symbols[i]);
                n -= values[i];
            }
        }
        return buffer.toString();
    }
}

No comments:

Post a Comment