My Java Implementation


  • -1
    C

    My solution, wanna some suggestions? Hope it to be simpler and clearer

    public class Solution {
    public String intToRoman(int num) {
    int[] units = {1000, 500, 100, 50, 10, 5, 1};
    char[] unitSymbol = {'M','D','C','L','X','V','I'};
    StringBuffer result = new StringBuffer("");
    int cur = num;
    int counter = 0;
    int nextUnit = 0;
    for(int i = 0; i<units.length; i++){
    if(cur == 0){
    break;
    }
    if(cur/units[i]>=1){
    counter = cur/units[i];
    for(int j =0; j<counter; j++){
    result.append(unitSymbol[i]);
    }
    }
    cur = cur%units[i];
    if(i!=units.length-1){
    if(units[i]/units[i+1]==2){
    nextUnit = i+2;
    }else{
    nextUnit = i+1;
    }
    if(cur>=units[i]-units[nextUnit]){
    result.append(unitSymbol[nextUnit]);
    result.append(unitSymbol[i]);
    cur = cur-(units[i]-units[nextUnit]);
    }

            }
        }
        return result.toString();
    }
    

    }


Log in to reply
 

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