[java] Convert Digit by digit as per decimal scan.

  • 0


    • Every digit (depending on its decimal position) has unique string sequence. Use this logic to generate roman equivalent.


    • From left to right pick digit by digit.
    • Find out the decimal position(0 for ones, 1 for tens, 2 for hundreds...)
    • Generate the roman equivalent.
    • Construct the result by pre-pending the generated sequence.
    class Solution {
        public String intToRoman(int num) {
            int pos = 0;  // 10 power equivalent of digit being scanned.
            String result = "";
            while (num>0) {
                int digit = num % 10;  // digit picked up for converstion
                result = DIGIT[pos][digit] + result;
                num = num/10;
            return result;
        String DIGIT[][] = {
            {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
            {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
            {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
            {"", "M", "MM", "MMM", "MW", "W", "WM", "WMM", "WMMM", "M?"},

Log in to reply

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