728x90
https://leetcode.com/problems/roman-to-integer/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int checkString(char a){
switch (a){
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
int romanToInt(string s){
int answer = 0;
for(int i=0; i<s.length(); i++){
if(i != s.length()-1){
if(s[i] == 'I' && s[i+1] == 'V') {
answer += 4; i++;
}
else if(s[i] == 'I' && s[i+1] == 'X') {
answer += 9; i++;
}
else if(s[i] == 'X' && s[i+1] == 'L') {
answer += 40; i++;
}
else if(s[i] == 'X' && s[i+1] == 'C') {
answer += 90; i++;
}
else if(s[i] == 'C' && s[i+1] == 'D') {
answer += 400; i++;
}
else if(s[i] == 'C' && s[i+1] == 'M') {
answer += 900; i++;
}
else answer += checkString(s[i]);
continue;
}
answer += checkString(s[i]);
}
return answer;
}
int main(){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cout << romanToInt("III") << '\n';
cout << romanToInt("LVIII") << '\n';
cout << romanToInt("MCMXCIV") << '\n';
}
좀 더 깔끔하게 할 수 있을 것 같았지만 if문을 사용해서 간단하게 구구절절 작성했다.
우선, 하나의 문자 말고 두 개의 문자를 하나로 봐야 할 경우가 있다. 이를 if문으로 체크해주면서 값을 answer에 합친다.
그리고 if 조건에 부합하지 않는다면 checkString 함수에서 해당 문자의 값을 받아와서 answer에 합쳐준다.
728x90
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode/easy] strStr() (0) | 2022.08.12 |
---|---|
[LeetCode/easy] Valid Parentheses (0) | 2022.08.12 |
[LeetCode/easy] Longest Common Prefix (0) | 2022.04.18 |
[LeetCode/easy] PalindromeNumber (0) | 2022.04.18 |
[LeetCode/easy] TwoSum (0) | 2022.04.18 |