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:
  5. string intToRoman(int num) {
  6. const int radix[] = {1000, 900, 500, 400, 100, 90,
  7. 50, 40, 10, 9, 5, 4, 1};
  8. const string symbol[] = {"M", "CM", "D", "CD", "C", "XC",
  9. "L", "XL", "X", "IX", "V", "IV", "I"};
  10. string roman;
  11. for (size_t i = 0; num > 0; ++i) {
  12. int count = num / radix[i];
  13. num %= radix[i];
  14. for (; count > 0; --count) roman += symbol[i];
  15. }
  16. return roman;
  17. }
  18. };

相关题目

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