[LeetCode] 13. Roman to Integer

영은히히·2021년 11월 5일

문제풀이

목록 보기
1/1

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

class Solution {
public:
    int romanToInt(string s) {
        int result = 0;
        for (int i = s.length(); i >= 0; i--) {
            char cstr = s[i];
            switch(cstr) {
            case 'I':
                result += 1;
                break;
            case 'V':
                if (i > 0 && s[i - 1] == 'I') {
                    result += 4;
                    i--;
                }
                else
                    result += 5;
                break;
            case 'X':
                if (i > 0 && s[i - 1] == 'I') {
                    result += 9;
                    i--;
                }
                else
                    result += 10;
                break;
            case 'L':
                if (i > 0 && s[i - 1] == 'X') {
                    result += 40;
                    i--;
                }
                else
                    result += 50;
                break;
            case 'C':
                if (i > 0 && s[i - 1] == 'X') {
                    result += 90;
                    i--;
                }
                else
                    result += 100;
                break;
            case 'D':
                if (i > 0 && s[i - 1] == 'C') {
                    result += 400;
                    i--;
                }
                else
                    result += 500;
                break;
            case 'M':
                if (i > 0 && s[i - 1] == 'C') {
                    result += 900;
                    i--;
                }
                else
                    result += 1000;
                break;
            }
        }
        return result;
    }
    
};

const template = {
firstStep: {
I: input, string
O: output, integer
C: constraints, 1 <= s.length <= 15,
문자열에는('I', 'V', 'X', 'L', 'C', 'D', 'M')만
E: edge cases
},
secondStep: {
DS: '',
Alg: '',
bruteForce: solution = (
1. 문자열을 뒤에서 부터 거꾸로 탐색
2. char array에 string 담기
3. switch문에 안에서 if문을 통해 다르게 계산하는 경우 나타냄
) => {
// pseudo code
}
time:
space:
}
thirdStep: {
DS: '',
Alg: '',
optimalSolution: solution = () => {
// pseudo code
},
time: O(),
space: O(),
},
fourthStep: {
actualSolution: () => {
/// Actual Code
}
},
fifthStep: {
testCases: (givenInput, expectedOutput, func) => {
const result = func(givenInput)
if(result === expectedOutput) {
println(SUCCESS(O))
} else {
println(FAILED(X))
}
}
}
}

profile
어차피 알아야 한다. 한 번에 하자

0개의 댓글