saurus2
Saurus2
saurus2
전체 방문자
오늘
어제
  • 분류 전체보기
    • 개발
      • AJAX
    • ML Ops
    • Profile
    • 음식점
    • 배낭여행
    • 컴퓨터공학
      • 알고리즘 공부
      • C++
      • Sever 스터디
      • Java spring
      • 알고리즘 _ 문제해결
      • 딥러닝
      • Java 정리
      • Python
      • LeetCode 1000
      • Machine Learning Study
      • Sign language Detection Pro..
      • LeetCode Solutions
    • 비콘
    • 데일리 리포트
    • 유학일기
      • 영어 공부
      • Daily
    • AI Master Degree
      • Data Mining
      • AI and Data engineering
      • Math Foundations for Decisi..
      • Natural Language Processing

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 온라인저지
  • 파이썬
  • two pointer
  • 리트코드
  • 딕셔너리
  • 개발자 취업준비
  • 문제해결능력
  • 알고리즘문제해결
  • BFS
  • DFS
  • 딥러닝
  • 알고리즘
  • 취업준비
  • 취준
  • LeetCode
  • Python
  • 개발자
  • c++
  • 백준
  • 릿코드

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
saurus2

Saurus2

컴퓨터공학/LeetCode 1000

[LeetCode] 13. Roman to Integer

2022. 8. 16. 11:36

13. Roman to Integer

Easy

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, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 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.

 

Example 1:

Input: s = "III"
Output: 3
Explanation: III = 3.

Example 2:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 3:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

 

Constraints:

  • 1 <= s.length <= 15
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].

문제 풀이

문제 접근

  1. 문장의 최대 길이는 15이기 때문에 시간 제한을 고민 하는 것은 의미가 없어 보인다.

풀이

  1. 모든 문자에 대해 다 확인해보는 것도 방법이다.
  2. 하지만, 소스 코드를 줄이는 방법을 생각해 보자.
  3. Roman 숫자의 규칙상 왼쪽에서부터 큰 숫자가 적히고 오른쪽으로 갈 수록 작은 숫자가 적힌다.
  4. 만일 왼쪽에서 오른쪽으로 확인을 할때 왼쪽에 작은 숫자가 있다면 그 숫자는 두자리 로만 숫자이다.
  5. 예시: IV 는 1, 5 이기 때문에 규칙상 각각 의 숫자로 존재 불가하다. 
    반대로 VI 는 5, 1 이기 때문에 존재할 수 있다. 
  6. 즉, 왼쪽부터 확인하면서 뒤에 숫자가 크다면 큰 숫자에서 작은 숫자를 빼주고 더 해주면 된다. 
  7. 예시: "LIV" -> 50, 1, 5.
    L > I < V, 50 + (5 - 1) 

소스 코드

class Solution:
    def romanToInt(self, s: str) -> int:
        symbols = {
            'I': 1,
            'V': 5,
            'X': 10,
            'L': 50,
            'C': 100,
            'D': 500,
            'M': 1000
        }
        ans = 0
        index = 0
        n = len(s)
        while index < n:
            if index + 1 < n and symbols[s[index]] < symbols[s[index + 1]]:
                ans += symbols[s[index + 1]] - symbols[s[index]]
                index += 2
            else:
                ans += symbols[s[index]]
                index += 1
        return ans
저작자표시 (새창열림)

'컴퓨터공학 > LeetCode 1000' 카테고리의 다른 글

[LeetCode] 5. Longest Palindromic Substring  (0) 2022.08.16
[LeetCode] 387. First Unique Character in a String  (0) 2022.08.16
[LeetCode] 90. Subsets II  (0) 2022.08.14
[LeetCode] 191. Number of 1 Bits  (0) 2022.08.14
[LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree  (0) 2022.08.12
    '컴퓨터공학/LeetCode 1000' 카테고리의 다른 글
    • [LeetCode] 5. Longest Palindromic Substring
    • [LeetCode] 387. First Unique Character in a String
    • [LeetCode] 90. Subsets II
    • [LeetCode] 191. Number of 1 Bits
    saurus2
    saurus2
    Simple is Best

    티스토리툴바