Integer to Roman
Posted tobeabetterpig
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Integer to Roman相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
Integer to Roman/Roman to Integer