Simple JAVA solution


  • 32
    O
    public String intToRoman(int num) {
        String M[] = {"", "M", "MM", "MMM"};
        String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
        String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
        String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
        return M[num/1000] + C[(num%1000)/100]+ X[(num%100)/10] + I[num%10];
    }

  • -1
    C

    Aren't you missing String M[] = {"", "M", "MM", "MMM", "MMMM"}; to capture 4K numbers.


  • 0
    J

    using stringbuilder will be much better.

    public class Solution {
        private static String M[] = {"","M","MM","MMM"};
        private static String C[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
        private static String X[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
        private static String I[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};
        public String intToRoman(int num) {
    	StringBuilder roman = new StringBuilder();
    	return roman.append(M[num/1000]).append(C[(num%1000)/100]).append(X[(num%100)/10]).append(I[num%10]).toString();
       }
    }

  • 0
    O

    In the que it is mentioned the int given as input are between 0 to 3999 so there will be no. 4k no


  • 2
    E

    My code is just like yours, but I'm using String instead of StringBuilder. My code also run as fast as yours. So I guess the reason your code run so fast is because of you define String arrays outside the method, not because of StringBuilder


  • 0
    J

    Maybe you're right.But it is fact that stringbuild is faster than string here in some ways.You can look for other relevant information on the internet.


  • 3
    C

    http://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java

    In this case, it doesn't really matter as long as you aren't concatenate strings in a loop, otherwise that makes not much different in terms of performance, more like personal style wise.


  • 1

    Any particular way to remember these array values


Log in to reply
 

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