1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RubyでLeetCodeを解いてみた Roman to Integer

Posted at

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

# @param {String} s
# @return {Integer}
def roman_to_int(s)
    arr = s.split("")
    last_idx = arr.size - 1
    sum = 0
    arr.each_with_index do |str, idx|
        case str
        when "I"
            if idx != last_idx && (arr[idx + 1] == "V" || arr[idx + 1] == "X")
                sum -= 1
            else
                sum += 1
            end
        when "V"
            sum += 5
        when "X"
            if idx != last_idx && (arr[idx + 1] == "L" || arr[idx + 1] == "C")
                sum -= 10
            else
                sum += 10
            end
        when "L"
            sum += 50
        when "C"
            if idx != last_idx && (arr[idx + 1] == "D" || arr[idx + 1] == "M")
                sum -= 100
            else
                sum += 100
            end
        when "D"
            sum += 500
        when "M"
            sum += 1000
        end
    end
    sum
end

馬鹿正直に実装してみた😛

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?