标签: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
标签:tco color HERE append htm com res bst discuss
原文地址:https://www.cnblogs.com/tobeabetterpig/p/9550685.html