Share my java solution with comments, no long listing


  • 0

    Well, I find the method which listing a lot of occurrence very clean. But I didn't come up with that. Hope my also solution helps:

    public String intToRoman(int num) {
        String[] romans = {"M", "D", "C", "L", "X", "V", "I"};
        int[] nums = {1000, 500, 100, 50, 10, 5, 1};
        int i = 0;
        int rem = num; 
        StringBuffer result = new StringBuffer();
        
        //consider corner case, the first letter 'M, since no letter before it:
        while(rem >= nums[i]) {  //makes num < 1000
            result.append(romans[i]);
            rem -= nums[i];
        }
        i++;
        
        while(rem > 0){
            //for C, X, M, the letter before it to do deduction
            // is X, I, C, who is ****2 letter**** after it in the array
            //each apears only once or none
            //the iterator i is the one step ahead, C, X, M, e.g. i=1 for M
            if(i%2 == 1){ //i is odd
                if(rem >= nums[i-1] - nums[i+1]){
                    result.append(romans[i+1]);
                    result.append(romans[i-1]); //e.g. "XC"
                    rem -= nums[i-1] - nums[i+1];
                }
                else if(rem >= nums[i]){
                    result.append(romans[i]); //e.g. "C"
                    rem -= nums[i];
                }
                else i++;
            }
            
            //for L, V, the letter before it to do deduction
            // is X, I, who is ****1 letter**** after it in the array
            //again, each apears only once or none
            else{//i%2==0 i is even,
                if(rem >= nums[i-1] - nums[i]){
                    result.append(romans[i]);
                    result.append(romans[i-1]); //e.g. "XL"
                    rem -= nums[i-1] -  nums[i];
                }
                else if(rem >= nums[i]){
                    result.append(romans[i]); //e.g. "L"
                    rem -= nums[i];
                }
                else i++;
            }
        }
        return result.toString();
    }

Log in to reply
 

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