Java solution


  • 0
    A
     public String intToRoman(int num) {
            int [] nums = {1000, 500, 100, 50, 10, 5, 1};
            char [] chars = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
    
            StringBuilder sb = new StringBuilder();
    
            for(int i = 0; i < nums.length && num != 0; i++) {
                if(num >= nums[i]) {
                    if (num / nums[i] > 3) {
                        num = num - nums[i - 1] + nums[i];
                        sb.append(chars[i]);
                        sb.append(chars[i - 1]);
                    }
                    else if (i % 2 == 1) {
                        if ((num - nums[i])/ nums[i + 1] > 3) {
                            num = num - nums[i - 1] + nums[i + 1];
                            sb.append(chars[i + 1]);
                            sb.append(chars[i - 1]);
                        } else {
                            num = num - nums[i];
                            sb.append(chars[i]);
                        }
                    }
                    else {
                        while(num/nums[i] > 0) {
                            num -= nums[i];
                            sb.append(chars[i]);
                        }
                    }
                }
            }
    
            return sb.toString();
        }
    

Log in to reply
 

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