Java not best time but easy readable solution using Map


  • 0
    S
    public class Solution {
    	private Map<Integer, String> romans = new HashMap<Integer,String>();
    	
    	private final int five = 5;
    	private final int ten = 10;
    	
    	public Solution(){
    		romans.put(1,"I");
    		romans.put(5,"V");
    		romans.put(10,"X");
    		romans.put(50,"L");
    		romans.put(100,"C");
    		romans.put(500,"D");
    		romans.put(1000,"M");
    	}
    	
        public String intToRoman(int num) {
    		StringBuilder roman = new StringBuilder();
    
    		int divider = 1000;
    		while(divider>0){
    			int n = num/divider;
    			
    			if(n==9 || n==4){
    				roman.append(romans.get(divider)).append(romans.get((n+1)*divider));
    				n = 0;
    			} else if(n/five>0){
    				roman.append(romans.get(five*divider));
    				n -=five;
    			}
    			for(int i = n; i>0; i--){
    				roman.append(romans.get(divider));
    			}
    		
    			num %= divider;
    			divider /= ten;
    		}
    	
            return roman.toString();
        }
    }

Log in to reply
 

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