12. Integer to Roman

Given an integer, convert it to a roman numeral.

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

This question belongs to a set of question, how to process numbers.

public class Solution {
    public String intToRoman(int n) {
        String[] symbol = new String[]{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        int[] value = new int[]{1000,900,500,400, 100, 90, 50, 40, 10, 9, 5, 4, 1};

        int i = 0;
        StringBuilder sb = new StringBuilder();
        for( i=0; n!= 0; i++){
            while(n >= value[i]){
                n -=aa value[i];
                sb.append(symbol[i]);
            }
        }

        return sb.toString();
    }
}
public class Solution {
    public String intToRoman(int num) {
        String[] symbol = new String[]{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        int[] value = new int[]{1000,900,500,400, 100, 90, 50, 40, 10, 9, 5, 4, 1};

        int k = 0;
        StringBuilder sb = new StringBuilder();
        while(num >= 0 && k < value.length){
            while(num >= value[k]){
                num -= value[k];
                sb.append(symbol[k]);
            }
            k++;
        }

        return sb.toString();
    }
}

results matching ""

    No results matching ""