0
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.

leet code easy Roman to Integer Approach 1: Left-to-Right Pass

Posted at

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

class Solution:
    def romanToInt(self, s: str) -> int:
#ローマ数字と数字の辞書を作りwhileループで検索していく
        v ={"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
        total = 0
        i = 0
        while i < len(s):
#この問題はの難しい点は、4,9の二つ。それ以外の時は、左から右に数字が小さくなっていく。そのため、下記では、左から右に数字が「大きくなる例外」だけifで条件分岐した。
            if i + 1 < len(s) and v[s[i]] < v[s[i + 1]]:
#例外の時 (IXなど)は、右側の数字(X)から左側の数字(I)を引いた値を、totalに加える。
                total += v[s[i+1]] - v[s[i]]
                i += 2
            else:
                total += v[s[i]]
                i += 1
        return total

0
0
0

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
0
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?