My solutions in JAVA


  • 11
    public String intToRoman(int num) {
        String data[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        int value[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1}, base = -1;
        StringBuilder result = new StringBuilder();
    
        for(int i = 0;i < data.length;i++){
            if((base=num/value[i])!=0){
                while(base--!=0)result.append(data[i]);
                num=num%value[i];
            }
        }
        return result.toString();
    }

  • 0
    Q

    Any idea why a % is better than simple subtraction?

    public String intToRoman(int num) {
        int[] divisors = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        String[] romans = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        
        StringBuilder sb = new StringBuilder();
    
        for (int i = 0; i < divisors.length; i ++) {
            int divisor = divisors[i];
            while (num / divisor != 0) {
                sb.append(romans[i]);
                num -= divisor;
            }
        }
    
        return sb.toString();
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.