Skip to content

12. Integer to Roman

https://leetcode.com/problems/integer-to-roman/

js
/**
 * @param {number} num
 * @return {string}
 */
var intToRoman = function(num) {
  var vals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
  var symbols = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
  var result = []

  for (let i = 0; num !== 0; i++) {
    while (num >= vals[i]) {
      num -= vals[i]
      result.push(symbols[i])
    }
  }

  return result.join('')
}
py
class Solution(object):

    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        vals = [
            1000, 900, 500, 400, 100, 90,
            50, 40, 10, 9, 5, 4, 1
        ]
        symbols = [
            'M', 'CM', 'D', 'CD', 'C', 'XC',
            'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'
        ]
        result = []
        i = 0
        while num > 0:
            while num >= vals[i]:
                num -= vals[i]
                result.append(symbols[i])
            i += 1
        return ''.join(result)
go
func intToRoman(num int) string {
	vals := []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
	symbols := []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}
	result := ""

	for i := 0; num != 0; i++ {
		for num >= vals[i] {
			num -= vals[i]
			result += symbols[i]
		}
	}

	return result
}