본문 바로가기

알고리즘/코드 연습

[LeetCode] Roman to Integer

반응형

Roman numerals

 

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

위의 Sybol이 주어지면 Symbol과 숫자를 대응하여 계산한 값을 구하는 알고리즘이다.

계산 규직은 다음과 같다.

 

자신의 다음에 있는 Symbol의 Value가 자신의 Value보다 더 크다면 자기자신은 -연산을 하고 반대의 경우에는 +연산을 한다.

EX)

input : "III"

output : "3" 

 

input : "IV"

output : "4"

input : "IX"

output : "9"

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public int romanToInt(String s) {
        int[] map = new int[256];
        map['I'= 1; map['V'= 5; map['X'= 10; map['L'= 50; map['C'= 100; map['D'= 500; map['M'= 1000;
 
        int ret = 0, pre = 1;
        for (int i = s.length()-1; i >= 0--i) {
            int cur = map[s.charAt(i)];
            System.out.println(cur);
 
            if (cur < pre) ret -= cur;
            else {
                pre = cur;
                ret += cur;
            }
        }
        return ret;
    }
}
cs

 

반응형

'알고리즘 > 코드 연습' 카테고리의 다른 글

[백준 - 1924] 2007년  (0) 2020.07.29
[백준 - 2798] 블랙잭  (0) 2020.07.24
[LeetCode] Palindrome Number  (0) 2020.07.20
[LeetCode] Reverse Integer  (0) 2020.07.20
[LeetCode] Two Sum  (0) 2020.07.20