본문 바로가기

알고리즘

[LeetCode] 13. Roman to Integer

https://leetcode.com/problems/roman-to-integer/

 

Roman to Integer - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

이거보다 좋은 코드를 잘 모르겠다 ㅋㅋ

object Solution {
    def romanToInt(s:String): Int = {
        if(s.isEmpty) 0
    else if (s.startsWith("CM")) 900 + romanToInt(s.substring(2))
    else if (s.startsWith("CD")) 400 + romanToInt(s.substring(2))
    else if (s.startsWith("XC")) 90 + romanToInt(s.substring(2))
    else if (s.startsWith("XL")) 40 + romanToInt(s.substring(2))
    else if (s.startsWith("IX")) 9 + romanToInt(s.substring(2))
    else if (s.startsWith("IV")) 4 + romanToInt(s.substring(2))
    else s(0) match {
      case 'I' => 1 + romanToInt(s.substring(1))
      case 'V' => 5 + romanToInt(s.substring(1))
      case 'X' => 10 + romanToInt(s.substring(1))
      case 'L' => 50 + romanToInt(s.substring(1))
      case 'C' => 100 + romanToInt(s.substring(1))
      case 'D' => 500 + romanToInt(s.substring(1))
      case 'M' => 1000 + romanToInt(s.substring(1))
        case _ => 0
    }
  }
}

'알고리즘' 카테고리의 다른 글

Leetcode 127 Word Letter  (0) 2022.02.12
백준 2098 외판원 순회문제  (0) 2022.02.06
백준(BOJ) 1765번 피자 굽기 자바(java)  (0) 2020.06.07
백준(BOJ) 1033번 칵테일  (0) 2020.05.08
백준(BOJ) 11585 속타는 저녁 메뉴  (0) 2020.03.06