Integer to Roman

描述

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

分析

代码

  1. // Integer to Roman
  2. // 时间复杂度O(num),空间复杂度O(1)
  3. class Solution {
  4. public String intToRoman(int num) {
  5. final int radix[] = {1000, 900, 500, 400, 100, 90,
  6. 50, 40, 10, 9, 5, 4, 1};
  7. final String symbol[] = {"M", "CM", "D", "CD", "C", "XC",
  8. "L", "XL", "X", "IX", "V", "IV", "I"};
  9. StringBuilder roman = new StringBuilder();
  10. for (int i = 0; num > 0; ++i) {
  11. int count = num / radix[i];
  12. num %= radix[i];
  13. for (; count > 0; --count) roman.append(symbol[i]);
  14. }
  15. return roman.toString();
  16. }
  17. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/string/integer-to-roman.html