DEV Community

Debesh P.
Debesh P.

Posted on

12. Integer to Roman | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/integer-to-roman/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/integer-to-roman/solutions/7439442/most-optimal-solution-beats-1000-o1-tc-s-8367


leetcode 12


Solution

class Solution {
    public String intToRoman(int num) {

        int[] values = {
            1000, 900, 500, 400,
            100, 90, 50, 40,
            10, 9, 5, 4,
            1
        };

        String[] symbols = {
            "M", "CM", "D", "CD",
            "C", "XC", "L", "XL",
            "X", "IX", "V", "IV",
            "I"
        };

        StringBuilder ans = new StringBuilder();

        for (int i = 0; i < values.length; i++) {
            while (num >= values[i]) {
                num -= values[i];
                ans.append(symbols[i]);
            }
        }

        return ans.toString();
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)