原题网址:https://leetcode.com/problems/integer-to-roman/
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
方法:理解罗马数字的规律。二分法。
public class Solution {
public String intToRoman(int num) {
StringBuilder sb = new StringBuilder();
int[] values = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
String[] romans = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};
while (num > 0) {
int i=0, j=values.length-1;
while (i<=j) {
int m = (i+j)/2;
if (values[m] <= num) {
i = m+1;
} else {
j = m-1;
}
}
int pos = i-1;
// System.out.printf("num=%d, values[pos]=%d, romans[pos]=%s\n", num, values[pos], romans[pos]);
sb.append(romans[pos]);
num -= values[pos];
}
return sb.toString();
}
}