Skip to content

Instantly share code, notes, and snippets.

@KevinSia
Created September 8, 2017 04:03
Show Gist options
  • Save KevinSia/fa494967a804a83636450c5bf3c314ec to your computer and use it in GitHub Desktop.
Save KevinSia/fa494967a804a83636450c5bf3c314ec to your computer and use it in GitHub Desktop.
def to_roman(num)
str = ''
# Your code here
if num >= 1000
str += 'M' * (num / 1000)
num %= 1000
end
if num == 900
str += 'CM'
num -= 900
end
if num >= 500
str += 'D'
num -= 500
end
if num >= 400
str += 'CD'
num -= 400
end
if num >= 100
str += 'C' * (num / 100)
num %= 100
end
if num >= 90
str += 'CX'
num -= 90
end
if num >= 50
str += 'L'
num -= 50
end
if num >= 40
str += 'XL'
num -= 40
end
if num >= 10
str += 'X' * (num / 10)
num %= 10
end
if num == 9
str += 'IX'
num -= 9
end
if num >= 5
str += 'V'
num -= 5
end
if num == 4
str += 'IV'
else
str + ('I' * num)
end
end
# Drive code... this should print out trues.
puts to_roman(1) == "I"
puts to_roman(3) == "III"
puts to_roman(6) == "VI"
puts to_roman(4) == "IV"
puts to_roman(9) == "IX"
puts to_roman(14) == "XIV"
puts to_roman(44) == "XLIV"
puts to_roman(944) == "CMXLIV"
# TODO: what other cases could you add to ensure your to_roman method is working?
def to_roman(num)
roman = %w(M CM D CD C CX L XL X IX V IV I)
numerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
str = ''
for i in 0..(roman.length - 1)
if num >= numerals[i]
str += roman[i] * (num / numerals[i])
num %= numerals[i]
end
end
str
end
# Drive code... this should print out trues.
puts to_roman(1) == "I"
puts to_roman(3) == "III"
puts to_roman(6) == "VI"
puts to_roman(4) == "IV"
puts to_roman(9) == "IX"
puts to_roman(14) == "XIV"
puts to_roman(44) == "XLIV"
puts to_roman(944) == "CMXLIV"
# TODO: what other cases could you add to ensure your to_roman method is working?
def to_roman(num)
romans = {"M"=>1000, "CM"=>900, "D"=>500, "CD"=>400, "C"=>100, "CX"=>90, "L"=>50, "XL"=>40, "X"=>10, "IX"=>9, "V"=>5, "IV"=>4, "I"=>1}
str = ''
romans.each do |roman, digit|
if num >= digit
str += roman * (num / digit)
num %= digit
end
end
str
end
# Drive code... this should print out trues.
puts to_roman(1) == "I"
puts to_roman(3) == "III"
puts to_roman(6) == "VI"
puts to_roman(4) == "IV"
puts to_roman(9) == "IX"
puts to_roman(14) == "XIV"
puts to_roman(44) == "XLIV"
puts to_roman(944) == "CMXLIV"
# TODO: what other cases could you add to ensure your to_roman method is working?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment