[LeetCode] 3.Roman to Integer
leetcode.com/problems/roman-to-integer/
1. Problem
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
For example, 2 is written as II in Roman numeral, just two one's 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
Example 2:
Input: s = "IV" Output: 4
Example 3:
Input: s = "IX" Output: 9
Example 4:
Input: s = "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3.
Example 5:
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].
2.Code
package leetCode;
public class RomanToInteger {
public static void main(String[] args) {
String s = "III";
//확인
System.out.print(romanToInt(s));
}
public static int romanToInt(String s) {
int sl = s.length();
int sum = 0;
for(int i = 0; i < sl; i++) {
if(s.charAt(i) == 'I'){
if(i != sl-1 && s.charAt(i+1) == 'V') {
sum = sum + 4;
i++;
} else if(i != sl-1 && s.charAt(i+1) == 'X') {
sum = sum + 9;
i++;
} else {
sum = sum + 1;
}
} else if(s.charAt(i) == 'V') {
sum = sum + 5;
} else if(s.charAt(i) == 'X') {
if(i != sl-1 && s.charAt(i+1) == 'L') {
sum = sum + 40;
i++;
} else if(i != sl-1 && s.charAt(i+1) == 'C') {
sum = sum + 90;
i++;
} else {
sum = sum + 10;
}
} else if(s.charAt(i) == 'L') {
sum = sum + 50;
} else if(s.charAt(i) == 'C') {
if(i != sl-1 && s.charAt(i+1) == 'D') {
sum = sum + 400;
i++;
} else if(i != sl-1 && s.charAt(i+1) == 'M') {
sum = sum + 900;
i++;
} else {
sum = sum + 100;
}
} else if(s.charAt(i) == 'D') {
sum = sum + 500;
} else if(s.charAt(i) == 'M') {
sum = sum + 1000;
}
}
return sum;
}
}
3. Report
특별할게 없었고.. Map을 써볼까 했지만 그냥 노가다..
더 간단하게 있지 않을까? 했으나 남들보다 99% 빠르다는거에 수긍ㅎ
'Algorithm > 문제' 카테고리의 다른 글
[LeetCode] 6.Merge Two SortedLists (0) | 2020.12.30 |
---|---|
[LeetCode] 5.Palindrome Number (0) | 2020.12.29 |
[LeetCode] 4.Reverse Integer (0) | 2020.12.28 |
[LeetCode] 2.Add Two Numbers (0) | 2020.12.28 |
[LeetCode] 1.TwoSum (0) | 2020.12.28 |