Does my way suck? (Java Solution)


  • 0
    S

    I see a lot of people using beautiful static arrays to deal with 4 and 9s.

    I didn't come up with that good idea. Instead, I only use 1 5 10, which specify a symbol, and each time checks for 4 and 9.

    I think I am more regarding it as a mathematics problem rather than a computer science problem. Can some body give any suggestions on my method?

    public class Solution {
        private static final char[] syms = {'I','V','X','L','C','D','M'};
        private static final int[] val = {1,5,10,50,100,500,1000}; 
        public String intToRoman(int num) {
            String s = "";
            int i = val.length-1;
            while(num!=0){
                int cur = num/val[i];
                int low = i > 0?num/val[i-1]:0;
                if(cur!=0){
                    if(cur==4){
                        s += syms[i];
                        s += syms[i+1];
                        num %=val[i];
                    }else if(low==9){
                        s += syms[i-1];
                        s += syms[i+1];
                        num %=val[i-1];
                    }else{
                        for(int j =0;j < cur;j++)
                            s += syms[i];
                        num %=val[i];
                    }
                }
                i--;
            }
            return s;
        }
    }

Log in to reply
 

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