My accepted solution in Java using array


  • 5
    A

    The key of my solution is count the num of every digits,and using array to append it.

    public class Solution {
        public String intToRoman(int num) {
            StringBuffer res=new StringBuffer();
            String[] aryC={"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
            String[] aryX={"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
            String[] aryI={"","I","II","III","IV","V","VI","VII","VIII","IX"};
            int Mnums=num/1000;        //1000
            int Cnums=(num%1000)/100;  //100
            int Xnums=(num%100)/10;    //10
            int Inums=num%10;          //1
            for(int i=Mnums;i>0;i--)
            {
                res.append("M");
            }
            res.append(aryC[Cnums]);
            res.append(aryX[Xnums]);
            res.append(aryI[Inums]);
            return res.toString();
        }
    }

Log in to reply
 

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