Share my java solution


  • 0
    M
    public class Solution {
        public String intToRoman(int num) {  // 1<=num<=3999
            char[][] map = new char[][] {{'I', 'V', 'X'}, {'X', 'L', 'C'}, {'C', 'D', 'M'}, {'M'}};
            StringBuilder sb = new StringBuilder();
            for (int p=0; num>0; ++p, num/=10) {  // p points to weight of 1, 10, 100, 1000
                 int d = num % 10;
                 if (d>0 && d<4) { for (int i=0; i<d; ++i) { sb.append(map[p][0]); } }
                 else if (d == 4) { sb.append(map[p][1]).append(map[p][0]); }
                 else if (d>4 && d<9) {
                     for (int i=0; i<d-5; ++i) { sb.append(map[p][0]); }
                     sb.append(map[p][1]);
                 } else if (d == 9) { sb.append(map[p][2]).append(map[p][0]); }
            }
            return sb.reverse().toString();
        }
    }

Log in to reply
 

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