LeetCode----Integer to Roman


Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
分析:
Roman to Integerの逆変換は、逆になると、前の問題より少し難しいです.問題の核心はどのようにいくつかの数を処理するか、例えば40、90900などで、それぞれの状況の処理をよく考えて、この問題も解決することができます.しかし、私はとても悪いpythonコードを書いて、ついでに見つけたC++コードを添付しました(https://github.com/soulmachine/leetcode ).
Pythonコード:
class Solution(object):
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        v_keys = {1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V', 6: 'VI', 7: 'VII', 8: 'VIII', 9: 'IX',
                  10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M'}
        if num in v_keys:
            return v_keys[num]
        r_num = ''  # the result (roman number)
        while True:
            n_range = self.numRange(num)
            if n_range in [1, 2, 8]:
                r_num += v_keys[num]
                break
            elif n_range == 3:
                r_num += 'X'
                num -= 10
            elif n_range == 4:
                r_num += 'L'
                num -= 50
            elif n_range == 5:
                r_num += 'C'
                num -= 100
            elif n_range == 6:
                r_num += 'D'
                num -= 500
            elif n_range == 7:
                r_num += 'M'
                num -= 1000
        r_num = self.check_roman(r_num)
        return r_num

    def numRange(self, num):
        if 1 <= num <= 5:
            return 1
        elif 5 < num <= 10:
            return 2
        elif 10 < num < 50:
            return 3
        elif 50 < num < 100:
            return 4
        elif 100 < num < 500:
            return 5
        elif 500 < num < 1000:
            return 6
        elif 1000 < num:
            return 7
        else:
            return 8

    def check_roman(self, r_num):
        r_num = r_num.replace('XXXX', 'XL')  # 40
        r_num = r_num.replace('CCCC', 'CD')  # 400
        r_num = r_num.replace('LXL', 'XC')  # 90
        r_num = r_num.replace('DCD', 'CM')  # 900
        return r_num

C++コード:
class Solution {
public:
      string intToRoman(int num) {
          const int radix[] = {1000, 900, 500, 400, 100, 90,
                  50, 40, 10, 9, 5, 4, 1};
          const string symbol[] = {"M", "CM", "D", "CD", "C", "XC",
                  "L", "XL", "X", "IX", "V", "IV", "I"};
          string roman;
          for (size_t i = 0; num > 0; ++i) {
              int count = num / radix[i];
              num %= radix[i];
              for (; count > 0; --count) roman += symbol[i];
          }
          return roman;
      }
};