I want to convert Roman numerals, such as "mcmxcix", to arabic integers like "1999".
My code looks like:
#~ I = 1 V = 5 X = 10 L = 50
#~ C = 100 D = 500 M = 1000
def roman_to_integer roman
len = roman.length
x = 1
while x <= len
arr = Array.new
arr.push roman[x]
x += 1
end
num = 0
arr.each do |i|
if i == 'I'
num += 1
elsif i == 'V'
num += 5
elsif i == 'X'
num += 10
elsif i == 'L'
num += 50
elsif i == 'C'
num += 100
elsif i == 'D'
num += 500
elsif i == 'M'
num += 1000
end
e开发者_如何学Cnd
num
end
puts(roman_to_integer('MCMXCIX'))
The output is 0, but I don't understand why?
Ruby doesn't have a post-increment operator. When it sees ++
it interprets that as one infix +
followed by one prefix (unary) +
. Since it expects an operand to follow after that, but instead finds the keyword end
, you get a syntax error.
You need to replace x++
with x += 1
.
Furthermore note that x
isn't actually in scope inside the roman_to_integer
method (which isn't a syntax error, but nevertheless wrong).
Additionally you'll have to replace all your if
s except the first with elsif
s. The way you wrote it all the if
s are nested, which means that a) you don't have enough end
s and b) the code doesn't have the semantics you want.
You are missing a closing parentheses so
puts(roman_to_integer('mcmxcix')
should be
puts roman_to_integer('mcmxcix')
or
puts(roman_to_integer('mcmxcix'))
The arr keeps getting annihilated in your while loop, and it is not in the scope outside of the loop. Move the following line above the while statement:
arr = Array.new
精彩评论