๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/Leetcode

[Leetcode,c++] Roman to Integer

by dkswnkk 2021. 11. 15.

๋ฌธ์ œ

 

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

 

์ฝ”๋“œ

class Solution {
public:
    int sum=0;

    int roman_to_int(char c1,char c2){
        bool flag = true;
        if(c1=='I'){
            if(c2=='V'){
                sum+=4;
                flag = false;
            }
            else if(c2 =='X'){
                sum+=9;
                flag = false;
            }
            else sum+=1;
        }
        else if(c1=='V') sum+= 5;
        else if(c1=='C'){
            if(c2=='D'){
                sum+=400;
                flag = false;
            }
            else if(c2 =='M'){
                sum+=900;
                flag = false;
            }
            else sum+=100;
        }
        else if(c1=='X'){
            if(c2=='L'){
                sum+=40;
                flag = false;
            }
            else if(c2 =='C'){
                sum+=90;
                flag = false;
            }
            else sum+=10;
        }
        else if(c1=='L') sum+=50;
        else if(c1=='D') sum+=500;
        else if(c1=='M') sum+=1000;

        return flag;
    }

    int romanToInt(string s) {
        for(int i=0; i<s.length(); i++){
            if(!roman_to_int(s[i],s[i+1])) i++;

        }
        return sum;
    }
};

 

ํ’€์ด

๋‹จ์ˆœ ๊ตฌํ˜„ ๋ฌธ์ œ์˜€์Šต๋‹ˆ๋‹ค.

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

๊ธฐ๋ณธ์ ์œผ๋กœ ์œ„์™€ ๊ฐ™์€ ๊ฐ’์œผ๋กœ ๋ณ€ํ™˜์„ ํ•ด์ฃผ๋ฉด ๋˜์ง€๋งŒ ์•„๋ž˜์™€ ๊ฐ™์ด I๋’ค์— V๋‚˜ X, X๋’ค์— L์ด๋‚˜ C, C๋’ค์— D๋‚˜ X๊ฐ€ ์˜ฌ ๊ฒฝ์šฐ์—๋Š” ์•„๋ž˜์™€ ๊ฐ™์€ ๊ฐ’์œผ๋กœ ๋ฐ˜ํ™˜ํ•ด์ค˜์•ผ ํ•ฉ๋‹ˆ๋‹ค.

 

'Algorithm ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป > Leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Leetcode,c++] Subsets II  (0) 2021.11.15
[Leetcode,c++] Rotate Image  (0) 2021.11.15
[Leetcode,c++] Permutations II  (0) 2021.11.15
[Leetcode,c++] Find First and Last Position of Element in Sorted Array  (0) 2021.11.14
[Leetcode,c++] Group Anagrams  (0) 2021.11.14
[Leetcode,c++] Next Permutation  (0) 2021.11.14

๋Œ“๊ธ€