로마자를 정수로 변환

로마자를 정수로 변환
GfG Practice에서 사용해 보세요.

로마 숫자를 나타내는 문자열 s가 주어지면 해당 정수 값을 찾습니다.
로마 숫자는 다음 기호를 사용하여 구성됩니다: I = 1 V = 5 X = 10 L = 50 C = 100 D = 500 및 M = 1000.
숫자는 일반적으로 특정 규칙에 따라 해당 값을 왼쪽에서 오른쪽으로 더하거나 빼서 이러한 기호를 결합하여 형성됩니다.

변환은 어떻게 이루어지나요?

  • 더 작은 값 기호가 빼기 전에 오는 경우. 그렇지 않으면 추가합니다.
  • IV에서 I는 V 앞에 오고 V는 더 큰 값 5를 갖습니다. 따라서 결과는 5 - 1 = 4입니다.
  • VI에서 V는 I 앞에 오고 I는 더 작은 값 1을 갖습니다. 따라서 결과는 5 + 1 = 6입니다.
  • II에서는 동일한 값을 가지므로 더하고 1 + 1 = 2를 얻습니다.
  • 문자가 2개를 초과하는 경우 왼쪽에서 오른쪽으로 순회하고 더 작은 값 문자 뒤에 더 큰 값 문자가 표시되는 경우에만 그룹화합니다. 예를 들어 MXVII는 1000 + 10 + 5 + 1 + 1 = 1017입니다. 그리고 XLVII는 (50 - 10) + 5 + 1 + 1 = 47입니다. L이 더 크고 X 뒤에 옵니다.

예:

입력: s = 'IX'
산출: 9
설명: IX는 10 - 1 = 9를 나타내는 로마 기호입니다.

입력: s = 'XL'
산출: 40
설명: XL은 50 - 10 = 40을 나타내는 로마 기호입니다.

입력: s = 'MCMIV'
산출: 1904년
설명: M은 1000 CM은 1000 - 100 = 900이고 IV는 4입니다. 따라서 총계는 1000 + 900 + 4 = 1904입니다.

목차

[예상 접근법 1] 반복 비교를 이용한 - O(n) 시간과 O(1) 공간

로마 숫자를 정수로 변환하는 아이디어는 문자열을 왼쪽에서 오른쪽으로 이동해야 한다는 것입니다. 각 기호에 대해 다음 기호(존재하는 경우)와 비교합니다. 현재 기호가 다음 기호보다 크거나 같으면 해당 값을 결과에 추가합니다. 그렇지 않으면 다음 기호 값에서 해당 값을 빼고 결과를 합계에 추가하고 다음 기호를 건너뜁니다.

C++
   #include          using     namespace     std  ;   // this function returns value of a Roman symbol   int     value  (  char     r  )     {      if     (  r     ==     'I'  )      return     1  ;      if     (  r     ==     'V'  )      return     5  ;      if     (  r     ==     'X'  )      return     10  ;      if     (  r     ==     'L'  )      return     50  ;      if     (  r     ==     'C'  )      return     100  ;      if     (  r     ==     'D'  )      return     500  ;      if     (  r     ==     'M'  )      return     1000  ;      return     -1  ;   }   // returns decimal value of roman numeral   int     romanToDecimal  (  string  &     s  )     {      int     res     =     0  ;         for     (  int     i     =     0  ;     i      <     s  .  length  ();     i  ++  )     {          // get value of current symbol      int     s1     =     value  (  s  [  i  ]);      // Compare with the next symbol if it exists      if     (  i     +     1      <     s  .  length  ())     {      int     s2     =     value  (  s  [  i     +     1  ]);      // if current value is greater or equal       // add it to result      if     (  s1     >=     s2  )     {      res     +=     s1  ;      }      else     {      // else add the difference and skip       // next symbol      res     +=     (  s2     -     s1  );      i  ++  ;      }      }      else     {      res     +=     s1  ;      }      }      return     res  ;   }   int     main  ()     {      string     s     =     'IX'  ;      cout      < <     romanToDecimal  (  s  )      < <     endl  ;      return     0  ;   }   
Java
   class   GfG     {      // this function returns value of a Roman symbol      static     int     value  (  char     r  )     {      if     (  r     ==     'I'  )      return     1  ;      if     (  r     ==     'V'  )      return     5  ;      if     (  r     ==     'X'  )      return     10  ;      if     (  r     ==     'L'  )      return     50  ;      if     (  r     ==     'C'  )      return     100  ;      if     (  r     ==     'D'  )      return     500  ;      if     (  r     ==     'M'  )      return     1000  ;      return     -  1  ;      }      // returns decimal value of roman numeral      static     int     romanToDecimal  (  String     s  )     {      int     res     =     0  ;         for     (  int     i     =     0  ;     i      <     s  .  length  ();     i  ++  )     {          //get value of current symbol      int     s1     =     value  (  s  .  charAt  (  i  ));      // compare with the next symbol if it exists      if     (  i     +     1      <     s  .  length  ())     {      int     s2     =     value  (  s  .  charAt  (  i     +     1  ));      // If current value is greater or equal       // add it to result      if     (  s1     >=     s2  )     {      res     +=     s1  ;      }      else     {      // else add the difference and skip       // next symbol      res     +=     (  s2     -     s1  );      i  ++  ;      }      }      else     {      res     +=     s1  ;      }      }      return     res  ;      }      public     static     void     main  (  String  []     args  )     {      String     s     =     'IX'  ;      System  .  out  .  println  (  romanToDecimal  (  s  ));      }   }   
Python
   # this function returns value of a Roman symbol   def   value  (  r  ):   if   r   ==   'I'  :   return   1   if   r   ==   'V'  :   return   5   if   r   ==   'X'  :   return   10   if   r   ==   'L'  :   return   50   if   r   ==   'C'  :   return   100   if   r   ==   'D'  :   return   500   if   r   ==   'M'  :   return   1000   return   -  1   # returns decimal value of roman numeral   def   romanToDecimal  (  s  ):   res   =   0   i   =   0   while   i    <   len  (  s  ):   # get value of current symbol   s1   =   value  (  s  [  i  ])   # compare with the next symbol if it exists   if   i   +   1    <   len  (  s  ):   s2   =   value  (  s  [  i   +   1  ])   # if current value is greater or equal    # add it to result   if   s1   >=   s2  :   res   +=   s1   else  :   # else add the difference and    # skip next symbol   res   +=   (  s2   -   s1  )   i   +=   1   else  :   res   +=   s1   i   +=   1   return   res   if   __name__   ==   '__main__'  :   s   =   'IX'   print  (  romanToDecimal  (  s  ))   
C#
   using     System  ;   class     GfG     {          // this function returns value of a Roman symbol      static     int     value  (  char     r  )     {      if     (  r     ==     'I'  )      return     1  ;      if     (  r     ==     'V'  )      return     5  ;      if     (  r     ==     'X'  )      return     10  ;      if     (  r     ==     'L'  )      return     50  ;      if     (  r     ==     'C'  )      return     100  ;      if     (  r     ==     'D'  )      return     500  ;      if     (  r     ==     'M'  )      return     1000  ;      return     -  1  ;      }      // returns decimal value of roman numeral      static     int     romanToDecimal  (  string     s  )     {      int     res     =     0  ;         for     (  int     i     =     0  ;     i      <     s  .  Length  ;     i  ++  )     {          // get value of current symbol      int     s1     =     value  (  s  [  i  ]);      // compare with the next symbol if it exists      if     (  i     +     1      <     s  .  Length  )     {      int     s2     =     value  (  s  [  i     +     1  ]);      // if current value is greater or equal       // add it to result      if     (  s1     >=     s2  )     {      res     +=     s1  ;      }      else     {      // else add the difference and skip      // next symbol      res     +=     (  s2     -     s1  );      i  ++  ;      }      }      else     {      res     +=     s1  ;      }      }      return     res  ;      }      static     void     Main  ()     {      string     s     =     'IX'  ;      Console  .  WriteLine  (  romanToDecimal  (  s  ));      }   }   
JavaScript
   // this function returns value of a Roman symbol   function     value  (  r  )     {      if     (  r     ===     'I'  )         return     1  ;      if     (  r     ===     'V'  )         return     5  ;      if     (  r     ===     'X'  )         return     10  ;      if     (  r     ===     'L'  )         return     50  ;      if     (  r     ===     'C'  )         return     100  ;      if     (  r     ===     'D'  )         return     500  ;      if     (  r     ===     'M'  )         return     1000  ;      return     -  1  ;   }   // returns decimal value of roman numeral   function     romanToDecimal  (  s  )     {      let     res     =     0  ;         for     (  let     i     =     0  ;     i      <     s  .  length  ;     i  ++  )     {          // get value of current symbol      let     s1     =     value  (  s  [  i  ]);      // compare with the next symbol if it exists      if     (  i     +     1      <     s  .  length  )     {      let     s2     =     value  (  s  [  i     +     1  ]);      // if current value is greater or equal       // add it to result      if     (  s1     >=     s2  )     {      res     +=     s1  ;      }      else     {      // else add the difference and       // skip next symbol      res     +=     (  s2     -     s1  );      i  ++  ;      }      }      else     {      res     +=     s1  ;      }      }      return     res  ;   }   // Driver Code   let     s     =     'IX'  ;      console  .  log  (  romanToDecimal  (  s  ));   

산출
9  

[예상 접근 방식 2] 해싱 활용 - O(n) 시간과 O(1) 공간

해시 맵이나 사전을 사용하여 로마 기호 값을 저장할 수 있습니다. 그리고 문제를 해결하려면 문자열을 반복하고 각 기호에 대해 현재 값이 다음 값보다 작은지 확인해야 합니다. 그렇다면 다음 값에서 현재 값을 빼고 그 결과를 합계에 더합니다. 그렇지 않으면 현재 값을 합계에 추가합니다.

C++
   #include          #include         using     namespace     std  ;   int     romanToDecimal  (  string     &  s  )     {      unordered_map   <  char       int  >     romanMap     =     {{  'I'       1  }         {  'V'       5  }         {  'X'       10  }         {  'L'       50  }      {  'C'       100  }         {  'D'       500  }         {  'M'       1000  }};      int     res     =     0  ;      for     (  int     i     =     0  ;     i      <     s  .  length  ();     i  ++  )     {      // if the current value is less than the next value       // subtract current from next and add to res      if     (  i     +     1      <     s  .  length  ()     &&     romanMap  [  s  [  i  ]]      <     romanMap  [  s  [  i     +     1  ]])     {      res     +=     romanMap  [  s  [  i     +     1  ]]     -     romanMap  [  s  [  i  ]];      // skip the next symbol      i  ++  ;      }      else     {      // otherwise add the current value to res      res     +=     romanMap  [  s  [  i  ]];      }      }      return     res  ;   }   int     main  ()     {      string     s     =     'IX'  ;      cout      < <     romanToDecimal  (  s  )      < <     endl  ;      return     0  ;   }   
Java
   import     java.util.HashMap  ;   class   GfG     {      static     int     romanToDecimal  (  String     s  )     {      HashMap   <  Character       Integer  >     romanMap     =     new     HashMap   <>  ();      romanMap  .  put  (  'I'       1  );      romanMap  .  put  (  'V'       5  );      romanMap  .  put  (  'X'       10  );      romanMap  .  put  (  'L'       50  );      romanMap  .  put  (  'C'       100  );      romanMap  .  put  (  'D'       500  );      romanMap  .  put  (  'M'       1000  );      int     res     =     0  ;      for     (  int     i     =     0  ;     i      <     s  .  length  ();     i  ++  )     {      // if the current value is less than the next value      // subtract current from next and add to res      if     (  i     +     1      <     s  .  length  ()     &&     romanMap  .  get  (  s  .  charAt  (  i  ))      <         romanMap  .  get  (  s  .  charAt  (  i     +     1  )))     {      res     +=     romanMap  .  get  (  s  .  charAt  (  i     +     1  ))     -         romanMap  .  get  (  s  .  charAt  (  i  ));      // skip the next symbol      i  ++  ;      }      else     {      // otherwise add the current value to res      res     +=     romanMap  .  get  (  s  .  charAt  (  i  ));      }      }      return     res  ;      }      public     static     void     main  (  String  []     args  )     {      String     s     =     'IX'  ;      System  .  out  .  println  (  romanToDecimal  (  s  ));      }   }   
Python
   def   romanToDecimal  (  s  ):   romanMap   =   {  'I'  :   1     'V'  :   5     'X'  :   10     'L'  :   50     'C'  :   100     'D'  :   500     'M'  :   1000  }   res   =   0   i   =   0   while   i    <   len  (  s  ):   # if the current value is less than the next value    # subtract current from next and add to res   if   i   +   1    <   len  (  s  )   and   romanMap  [  s  [  i  ]]    <   romanMap  [  s  [  i   +   1  ]]:   res   +=   romanMap  [  s  [  i   +   1  ]]   -   romanMap  [  s  [  i  ]]   # skip the next symbol   i   +=   1   else  :   # otherwise add the current value to res   res   +=   romanMap  [  s  [  i  ]]   i   +=   1   return   res   if   __name__   ==   '__main__'  :   s   =   'IX'   print  (  romanToDecimal  (  s  ))   
C#
   using     System  ;   using     System.Collections.Generic  ;   class     GfG     {      static     int     romanToDecimal  (  string     s  )     {          // create a map to store the Roman numeral values      Dictionary   <  char       int  >     romanMap     =         new     Dictionary   <  char       int  >     {      {  'I'       1  }     {  'V'       5  }     {  'X'       10  }     {  'L'       50  }      {  'C'       100  }     {  'D'       500  }     {  'M'       1000  }      };      int     res     =     0  ;      for     (  int     i     =     0  ;     i      <     s  .  Length  ;     i  ++  )     {          // if the current value is less than the next value       // subtract current from next and add to res      if     (  i     +     1      <     s  .  Length     &&     romanMap  [  s  [  i  ]]      <     romanMap  [  s  [  i     +     1  ]])     {      res     +=     romanMap  [  s  [  i     +     1  ]]     -     romanMap  [  s  [  i  ]];      // skip the next symbol      i  ++  ;      }      else     {          // otherwise add the current value to res      res     +=     romanMap  [  s  [  i  ]];      }      }      return     res  ;      }      static     void     Main  ()     {      string     s     =     'IX'  ;      Console  .  WriteLine  (  romanToDecimal  (  s  ));      }   }   
JavaScript
   function     romanToDecimal  (  s  )     {          // create a map to store the Roman numeral values      const     romanMap     =     {      'I'  :     1       'V'  :     5       'X'  :     10       'L'  :     50        'C'  :     100       'D'  :     500       'M'  :     1000      };      let     res     =     0  ;      for     (  let     i     =     0  ;     i      <     s  .  length  ;     i  ++  )     {      // if the current value is less than the next value       // subtract current from next and add to res      if     (  i     +     1      <     s  .  length     &&     romanMap  [  s  [  i  ]]      <     romanMap  [  s  [  i     +     1  ]])     {      res     +=     romanMap  [  s  [  i     +     1  ]]     -     romanMap  [  s  [  i  ]];      // skip the next symbol      i  ++  ;      }      else     {      // otherwise add the current value to res      res     +=     romanMap  [  s  [  i  ]];      }      }      return     res  ;   }   // Driver Code   let     s     =     'IX'  ;   console  .  log  (  romanToDecimal  (  s  ));   

산출
9