码迷,mamicode.com
首页 > 其他好文 > 详细

Integer to Roman

时间:2018-08-28 21:19:14      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:tco   color   HERE   append   htm   com   res   bst   discuss   

Integer to Roman
http://bangbingsyb.blogspot.com/2014/11/leetcode-integer-to-roman.html

https://www.youtube.com/watch?v=LBsvAwQbVdw




class Solution {
    
    private static final String[] numerals = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", 
                                                         "X", "IX", "V", "IV", "I"};
    
    private static final int[] values = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    
    public String intToRoman(int value) {
        // discuss with interview about the range 
        // if(value > 3999 || value < 1) throw new IllegalArgumentException();
        StringBuilder numeral = new StringBuilder();
        int i = 0;
        while(value > 0){
            if(value - values[i] >= 0){
                numeral.append(numerals[i]);
                value = value - values[i];
            }else{
                // when the left over is smaller than 0, we move to the next smaller substraction 
                i++;
            }
        }
        return numeral.toString();
    }
}
        

// idea : the numbers in the values are the ones that we substract from the input every time from the 
// largest 1000 to lowest 1. since there are cases like 900, 400, 90, 40, 9, 4 , 
// these numbers roman representations are different from , say 800, 300,700, 
// 900 = 1000 - 100
// 400 = 500 - 100
// 40 = 50 - 10
// 9 = 10 - 1
// 90 = 100 - 10

// 8 = 5 + 3
// 800 = 500 + 300
// 700 = 500 + 200

// 3 = 1 + 1 + 1 
// 42 = 40 + 1 + 1 

// 49 = 40 + 9 

 

Integer to Roman

标签:tco   color   HERE   append   htm   com   res   bst   discuss   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9550685.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!