Conversione del numero decimale compreso tra 1 e 3999 in numeri romani

Conversione del numero decimale compreso tra 1 e 3999 in numeri romani
Provalo su GfG Practice

Dato un numero intero convertirlo nella sua rappresentazione in numero romano equivalente.

Nota: Di seguito è riportato l'elenco dei simboli romani (compresi i casi sottrattivi):

Simbolo Valore
IO 1
IV 4
V 5
IX 9
X 10
XL 40
l 50
XC 90
C 100
CD 400
D 500
CM 900
M 1000

Esempi: 

Ingresso: 9
Produzione: IX
Spiegazione: 9 è scritto come 'IX' in numeri romani utilizzando la notazione sottrattiva, ponendo un numero più piccolo prima di uno più grande.

  • I = 1 X = 10
  • IX significa 10 - 1 = 9

Ingresso: 40
Produzione: XL
Spiegazione: 40 è scritto come "XL" in numeri romani utilizzando la notazione sottrattiva, ovvero posizionando un numero più piccolo prima di uno più grande.

  • X = 10 litri = 50
  • XL significa 50 - 10 = 40

[Soluzione per scopi generali] - Tempo O(n) e Spazio O(n).

Confronta il numero dato con i valori base nell'ordine 1000 900 500 400 100 90 50 40 10 9 5 4 1. Una volta trovato il valore base più grande che è inferiore al numero dato, dividiamo il numero con il valore base e ripetiamo il processo per valori base e quoziente più piccoli. Aggiungiamo al risultato il simbolo romano corrispondente al valore base trovato il numero di volte uguale al quoziente e ripetiamo il procedimento per il resto.

Cerchiamo di comprendere l'approccio con l'esempio 3549

Iterazione 1

  • Dal 3549 >= 1000 ; il valore base più grande sarà inizialmente 1000.
  • Dividere 3549/1000. Quoziente = 3 res = 'MMM' (la nota M appartiene a 1000)
  • Resto = 549

Iterazione 2

  • 1000 > 549 >= 500 ; il valore base più grande sarà 500.
  • Dividere 549/500. Ogni volta = 1 .res = '300'
  • Resto = 49

Iterazione 3

  • 50 > 49 >= 40 ; il valore base più grande è 40.
  • Dividi 49/40. Quoziente = 1 res = 'MMMDXL'
  • Resto = 9.

Iterazione 4

  • Il numero 9 è presente nell'elenco. ris = 'MMMDXL'
  • Resto = 0.
C++
   #include          using     namespace     std  ;   // Function to convert decimal to Roman Numerals   string     toRoman  (  int     x  )     {      // array of values and symbols      vector   <  int  >     base     =     {  1       4       5       9       10       40       50       90       100       400       500       900       1000  };      vector   <  string  >     sym     =     {  'I'       'IV'       'V'       'IX'       'X'       'XL'       'L'       'XC'       'C'       'CD'       'D'       'CM'       'M'  };      // to store result      string     res     =     ''  ;      // Loop from the right side to find      // the largest smaller base value      int     i     =     base  .  size  ()     -     1  ;      while     (  x     >     0  )     {      int     div     =     x     /     base  [  i  ];      while     (  div  )     {      res     +=     sym  [  i  ];      div  --  ;      }          // Repeat the process for remainder      x     =     x     %     base  [  i  ];          i  --  ;      }      return     res  ;   }   int     main  ()     {      int     x     =     3549  ;      cout      < <     toRoman  (  x  );      return     0  ;   }   
Java
   // Function to convert decimal to Roman Numerals   public     class   RomanConverter     {      public     static     String     toRoman  (  int     x  )     {          // array of values and symbols      int  []     base     =     {  1       4       5       9       10       40       50       90       100       400       500       900       1000  };      String  []     sym     =     {  'I'       'IV'       'V'       'IX'       'X'       'XL'       'L'       'XC'       'C'       'CD'       'D'       'CM'       'M'  };      // to store result      StringBuilder     res     =     new     StringBuilder  ();      // Loop from the right side to find      // the largest smaller base value      int     i     =     base  .  length     -     1  ;      while     (  x     >     0  )     {      int     div     =     x     /     base  [  i  ]  ;      while     (  div     >     0  )     {      res  .  append  (  sym  [  i  ]  );      div  --  ;      }          // Repeat the process for remainder      x     =     x     %     base  [  i  ]  ;      i  --  ;      }      return     res  .  toString  ();      }      public     static     void     main  (  String  []     args  )     {      int     x     =     3549  ;      System  .  out  .  println  (  toRoman  (  x  ));      }   }   
Python
   # Function to convert decimal to Roman Numerals   def   to_roman  (  x  ):   # array of values and symbols   base   =   [  1     4     5     9     10     40     50     90     100     400     500     900     1000  ]   sym   =   [  'I'     'IV'     'V'     'IX'     'X'     'XL'     'L'     'XC'     'C'     'CD'     'D'     'CM'     'M'  ]   # to store result   res   =   ''   # Loop from the right side to find   # the largest smaller base value   i   =   len  (  base  )   -   1   while   x   >   0  :   div   =   x   //   base  [  i  ]   while   div  :   res   +=   sym  [  i  ]   div   -=   1   # Repeat the process for remainder   x   %=   base  [  i  ]   i   -=   1   return   res   x   =   3549   print  (  to_roman  (  x  ))   
C#
   // Function to convert decimal to Roman Numerals   public     class     RomanConverter     {      public     static     string     ToRoman  (  int     x  )     {          // array of values and symbols      int  []     baseValues     =     {  1       4       5       9       10       40       50       90       100       400       500       900       1000  };      string  []     symbols     =     {  'I'       'IV'       'V'       'IX'       'X'       'XL'       'L'       'XC'       'C'       'CD'       'D'       'CM'       'M'  };      // to store result      string     res     =     ''  ;      // Loop from the right side to find      // the largest smaller base value      int     i     =     baseValues  .  Length     -     1  ;      while     (  x     >     0  )     {      int     div     =     x     /     baseValues  [  i  ];      while     (  div     >     0  )     {      res     +=     symbols  [  i  ];      div  --  ;      }          // Repeat the process for remainder      x     %=     baseValues  [  i  ];      i  --  ;      }      return     res  ;      }      public     static     void     Main  ()     {      int     x     =     3549  ;      Console  .  WriteLine  (  ToRoman  (  x  ));      }   }   
JavaScript
   // Function to convert decimal to Roman Numerals   function     toRoman  (  x  )     {          // array of values and symbols      const     base     =     [  1       4       5       9       10       40       50       90       100       400       500       900       1000  ];      const     sym     =     [  'I'       'IV'       'V'       'IX'       'X'       'XL'       'L'       'XC'       'C'       'CD'       'D'       'CM'       'M'  ];      // to store result      let     res     =     ''  ;      // Loop from the right side to find      // the largest smaller base value      let     i     =     base  .  length     -     1  ;      while     (  x     >     0  )     {      let     div     =     Math  .  floor  (  x     /     base  [  i  ]);      while     (  div  )     {      res     +=     sym  [  i  ];      div  --  ;      }          // Repeat the process for remainder      x     %=     base  [  i  ];      i  --  ;      }      return     res  ;   }   let     x     =     3549  ;   console  .  log  (  toRoman  (  x  ));   

Produzione
MMMDXLIX 

Complessità temporale: O(n) dove n è la lunghezza della stringa di risposta che memorizza la conversione.
Spazio ausiliario: SU)

[Per intervallo limitato] - O(n) Tempo e O(n) Spazio

L'idea si basa sul fatto che abbiamo un intervallo limitato da 0 a 3999. Isoliamo le cifre corrispondenti alle migliaia e centinaia di decine e unità e quindi mappiamo ciascuna cifra al rispettivo numero romano equivalente in base al suo valore posizionale.

  • Memorizza le mappature del carattere M per diversi quozienti 0 1 2 3
  • Memorizza le mappature di C L e I per diversi quozienti da 0 a 9.

Utilizzando le mappature precedenti generiamo direttamente la stringa del risultato.

C++
   #include          using     namespace     std  ;   // Function to convert decimal to Roman Numerals   string     toRoman  (  int     val  )     {         // storing roman values of digits from 0-9      // when placed at different places      vector   <  string  >     m     =     {  ''       'M'       'MM'       'MMM'  };      vector   <  string  >     c     =     {  ''       'C'       'CC'       'CCC'       'CD'        'D'       'DC'       'DCC'       'DCCC'       'CM'  };      vector   <  string  >     x     =     {  ''       'X'       'XX'       'XXX'       'XL'        'L'       'LX'       'LXX'       'LXXX'       'XC'  };      vector   <  string  >     i     =     {  ''       'I'       'II'       'III'       'IV'        'V'       'VI'       'VII'       'VIII'       'IX'  };      // Converting to roman      string     thousands     =     m  [  val     /     1000  ];      string     hundreds     =     c  [(  val     %     1000  )     /     100  ];      string     tens     =     x  [(  val     %     100  )     /     10  ];      string     ones     =     i  [  val     %     10  ];      string     ans     =     thousands     +     hundreds     +     tens     +     ones  ;      return     ans  ;   }   int     main  ()     {      int     val     =     3549  ;      cout      < <     toRoman  (  val  );      return     0  ;   }   
Java
   import     java.util.*  ;   public     class   GfG     {      // Function to convert decimal to Roman Numerals      public     static     String     toRoman  (  int     val  )     {         // storing roman values of digits from 0-9      // when placed at different places      String  []     m     =     {  ''       'M'       'MM'       'MMM'  };      String  []     c     =     {  ''       'C'       'CC'       'CCC'       'CD'        'D'       'DC'       'DCC'       'DCCC'       'CM'  };      String  []     x     =     {  ''       'X'       'XX'       'XXX'       'XL'        'L'       'LX'       'LXX'       'LXXX'       'XC'  };      String  []     i     =     {  ''       'I'       'II'       'III'       'IV'        'V'       'VI'       'VII'       'VIII'       'IX'  };      // Converting to roman      String     thousands     =     m  [  val     /     1000  ]  ;      String     hundreds     =     c  [  (  val     %     1000  )     /     100  ]  ;      String     tens     =     x  [  (  val     %     100  )     /     10  ]  ;      String     ones     =     i  [  val     %     10  ]  ;      String     ans     =     thousands     +     hundreds     +     tens     +     ones  ;      return     ans  ;      }      public     static     void     main  (  String  []     args  )     {      int     val     =     3549  ;      System  .  out  .  println  (  toRoman  (  val  ));      }   }   
Python
   # Function to convert decimal to Roman Numerals   def   toRoman  (  val  ):   # storing roman values of digits from 0-9   # when placed at different places   m   =   [  ''     'M'     'MM'     'MMM'  ]   c   =   [  ''     'C'     'CC'     'CCC'     'CD'     'D'     'DC'     'DCC'     'DCCC'     'CM'  ]   x   =   [  ''     'X'     'XX'     'XXX'     'XL'     'L'     'LX'     'LXX'     'LXXX'     'XC'  ]   i   =   [  ''     'I'     'II'     'III'     'IV'     'V'     'VI'     'VII'     'VIII'     'IX'  ]   # Converting to roman   thousands   =   m  [  val   //   1000  ]   hundreds   =   c  [(  val   %   1000  )   //   100  ]   tens   =   x  [(  val   %   100  )   //   10  ]   ones   =   i  [  val   %   10  ]   ans   =   thousands   +   hundreds   +   tens   +   ones   return   ans   if   __name__   ==   '__main__'  :   val   =   3549   print  (  toRoman  (  val  ))   
C#
   using     System  ;   public     class     GfG     {      // Function to convert decimal to Roman Numerals      public     static     string     toRoman  (  int     val  )     {         // storing roman values of digits from 0-9      // when placed at different places      string  []     m     =     {  ''       'M'       'MM'       'MMM'  };      string  []     c     =     {  ''       'C'       'CC'       'CCC'       'CD'        'D'       'DC'       'DCC'       'DCCC'       'CM'  };      string  []     x     =     {  ''       'X'       'XX'       'XXX'       'XL'        'L'       'LX'       'LXX'       'LXXX'       'XC'  };      string  []     i     =     {  ''       'I'       'II'       'III'       'IV'        'V'       'VI'       'VII'       'VIII'       'IX'  };      // Converting to roman      string     thousands     =     m  [  val     /     1000  ];      string     hundreds     =     c  [(  val     %     1000  )     /     100  ];      string     tens     =     x  [(  val     %     100  )     /     10  ];      string     ones     =     i  [  val     %     10  ];      string     ans     =     thousands     +     hundreds     +     tens     +     ones  ;      return     ans  ;      }      public     static     void     Main  (  string  []     args  )     {      int     val     =     3549  ;      Console  .  WriteLine  (  toRoman  (  val  ));      }   }   
JavaScript
   // Function to convert decimal to Roman Numerals   function     toRoman  (  val  )     {         // storing roman values of digits from 0-9      // when placed at different places      let     m     =     [  ''       'M'       'MM'       'MMM'  ];      let     c     =     [  ''       'C'       'CC'       'CCC'       'CD'        'D'       'DC'       'DCC'       'DCCC'       'CM'  ];      let     x     =     [  ''       'X'       'XX'       'XXX'       'XL'        'L'       'LX'       'LXX'       'LXXX'       'XC'  ];      let     i     =     [  ''       'I'       'II'       'III'       'IV'        'V'       'VI'       'VII'       'VIII'       'IX'  ];      // Converting to roman      let     thousands     =     m  [  Math  .  floor  (  val     /     1000  )];      let     hundreds     =     c  [  Math  .  floor  ((  val     %     1000  )     /     100  )];      let     tens     =     x  [  Math  .  floor  ((  val     %     100  )     /     10  )];      let     ones     =     i  [  val     %     10  ];      let     ans     =     thousands     +     hundreds     +     tens     +     ones  ;      return     ans  ;   }   let     val     =     3549  ;   console  .  log  (  toRoman  (  val  ));   

Produzione
MMMDXLIX