Kleinste Zahl mit gegebener Zifferzahl und Summe

Kleinste Zahl mit gegebener Zifferzahl und Summe
Probieren Sie es bei der GFG -Praxis aus

Mit zwei Ganzzahlen S Und D finde die kleinste mögliche Zahl, die genau hat D Ziffern und a Summe der Ziffern gleich S .
Geben Sie die Nummer als eine zurück Saite . Wenn keine solche Zahl existiert '-1' .

Beispiele:

Eingang: S = 9 d = 2
Ausgabe: 18
Erläuterung: 18 ist die kleinstmögliche Zahl mit der Summe der Ziffern = 9 und insgesamt Ziffern = 2.

Eingang: S = 20 d = 3
Ausgabe: 299
Erläuterung: 299 ist die kleinstmögliche Zahl mit der Summe der Ziffern = 20 und insgesamt Ziffern = 3.

Eingang: S = 1 d = 1
Ausgabe: 1
Erläuterung: 1 ist die kleinstmögliche Zahl mit der Summe der Ziffern = 1 und insgesamt Ziffern = 1.

Inhaltstabelle

[Brute -Force -Ansatz] ITREAT ITREFTENTIERT - O (D*(10^D)) Zeit und o (1) Raum

Da sind Zahlen sequentiell die Brute Force -Ansatz Iterates aus dem kleinste D-Digit-Nummer an die größte jeden einzelnen überprüfen. Für jede Zahl berechnen wir die Summe seiner Ziffern und geben Sie die erste gültige Übereinstimmung zurück, um sicherzustellen, dass die kleinstmögliche Zahl ausgewählt ist. Wenn keine gültige Nummer vorliegt, kehren wir zurück '-1' .

C++
   // C++ program to find the smallest d-digit   // number with the given sum using    // a brute force approach   #include          using     namespace     std  ;   string     smallestNumber  (  int     s       int     d  )     {          // The smallest d-digit number is 10^(d-1)      int     start     =     pow  (  10       d     -     1  );          // The largest d-digit number is 10^d - 1      int     end     =     pow  (  10       d  )     -     1  ;      // Iterate through all d-digit numbers      for     (  int     num     =     start  ;     num      <=     end  ;     num  ++  )     {          int     sum     =     0       x     =     num  ;      // Calculate sum of digits      while     (  x     >     0  )     {      sum     +=     x     %     10  ;      x     /=     10  ;      }      // If sum matches return the number      // as a string      if     (  sum     ==     s  )     {      return     to_string  (  num  );      }      }      // If no valid number is found return '-1'      return     '-1'  ;   }   // Driver Code   int     main  ()     {          int     s     =     9       d     =     2  ;          cout      < <     smallestNumber  (  s       d  )      < <     endl  ;      return     0  ;   }   
Java
   // Java program to find the smallest d-digit   // number with the given sum using    // a brute force approach   import     java.util.*  ;   class   GfG     {          static     String     smallestNumber  (  int     s       int     d  )     {          // The smallest d-digit number is 10^(d-1)      int     start     =     (  int  )     Math  .  pow  (  10       d     -     1  );          // The largest d-digit number is 10^d - 1      int     end     =     (  int  )     Math  .  pow  (  10       d  )     -     1  ;      // Iterate through all d-digit numbers      for     (  int     num     =     start  ;     num      <=     end  ;     num  ++  )     {          int     sum     =     0       x     =     num  ;      // Calculate sum of digits      while     (  x     >     0  )     {      sum     +=     x     %     10  ;      x     /=     10  ;      }      // If sum matches return the number      // as a string      if     (  sum     ==     s  )     {      return     Integer  .  toString  (  num  );      }      }      // If no valid number is found return '-1'      return     '-1'  ;      }      // Driver Code      public     static     void     main  (  String  []     args  )     {          int     s     =     9       d     =     2  ;          System  .  out  .  println  (  smallestNumber  (  s       d  ));      }   }   
Python
   # Python program to find the smallest d-digit   # number with the given sum using    # a brute force approach   def   smallestNumber  (  s     d  ):   # The smallest d-digit number is 10^(d-1)   start   =   10  **  (  d   -   1  )   # The largest d-digit number is 10^d - 1   end   =   10  **  d   -   1   # Iterate through all d-digit numbers   for   num   in   range  (  start     end   +   1  ):   sum_digits   =   0   x   =   num   # Calculate sum of digits   while   x   >   0  :   sum_digits   +=   x   %   10   x   //=   10   # If sum matches return the number   # as a string   if   sum_digits   ==   s  :   return   str  (  num  )   # If no valid number is found return '-1'   return   '-1'   # Driver Code   if   __name__   ==   '__main__'  :   s     d   =   9     2   print  (  smallestNumber  (  s     d  ))   
C#
   // C# program to find the smallest d-digit   // number with the given sum using    // a brute force approach   using     System  ;   class     GfG     {          static     string     smallestNumber  (  int     s       int     d  )     {          // The smallest d-digit number is 10^(d-1)      int     start     =     (  int  )  Math  .  Pow  (  10       d     -     1  );          // The largest d-digit number is 10^d - 1      int     end     =     (  int  )  Math  .  Pow  (  10       d  )     -     1  ;      // Iterate through all d-digit numbers      for     (  int     num     =     start  ;     num      <=     end  ;     num  ++  )     {          int     sum     =     0       x     =     num  ;      // Calculate sum of digits      while     (  x     >     0  )     {      sum     +=     x     %     10  ;      x     /=     10  ;      }      // If sum matches return the number      // as a string      if     (  sum     ==     s  )     {      return     num  .  ToString  ();      }      }      // If no valid number is found return '-1'      return     '-1'  ;      }      // Driver Code      public     static     void     Main  ()     {          int     s     =     9       d     =     2  ;          Console  .  WriteLine  (  smallestNumber  (  s       d  ));      }   }   
JavaScript
   // JavaScript program to find the smallest d-digit   // number with the given sum using    // a brute force approach   function     smallestNumber  (  s       d  )     {          // The smallest d-digit number is 10^(d-1)      let     start     =     Math  .  pow  (  10       d     -     1  );          // The largest d-digit number is 10^d - 1      let     end     =     Math  .  pow  (  10       d  )     -     1  ;      // Iterate through all d-digit numbers      for     (  let     num     =     start  ;     num      <=     end  ;     num  ++  )     {          let     sum     =     0       x     =     num  ;      // Calculate sum of digits      while     (  x     >     0  )     {      sum     +=     x     %     10  ;      x     =     Math  .  floor  (  x     /     10  );      }      // If sum matches return the number      // as a string      if     (  sum     ===     s  )     {      return     num  .  toString  ();      }      }      // If no valid number is found return '-1'      return     '-1'  ;   }   // Driver Code   let     s     =     9       d     =     2  ;   console  .  log  (  smallestNumber  (  s       d  ));   

Ausgabe
18  

[Erwarteter Ansatz] Verwenden der gierigen Technik - O (d) Zeit und o (1) Raum

Der Ansatz sorgt für die Ziffer links in der linken Seite ist ungleich Null Also wir Reserve 1 dafür und verteilt die verbleibende Summe von rechts nach links um die kleinstmögliche Zahl zu bilden. Der gieriger Ansatz hilft bei der Platzierung der größtmöglichen Werte (bis zu 9) am rechts die Positionen rechts um die Zahl klein zu halten.

Schritte zur Implementierung der obigen Idee:

  • Überprüfen Sie die Einschränkungen, um a zu gewährleisten gültige Summe s Kann mit Verwendung gebildet werden D Ziffern ansonsten zurückkehren '-1' .
  • Initialisieren Ergebnis als eine Reihe von D '0's Und Reserve 1 für die Links die Ziffer links durch Reduzierung s durch 1 .
  • Überqueren von rechts nach links und platzieren die größtmögliche Ziffer ( <= 9) beim Aktualisieren S entsprechend.
  • Wenn S <= 9 Platzieren Sie seinen Wert an die aktuelle Position und setzen Sie S = 0 Weitere Updates einstellen.
  • Zuweisen Sie die Links die Ziffer links durch Hinzufügen des restliche s Um sicherzustellen, dass es bleibt ungleich Null .
  • Konvertieren die Ergebnis Zeichenfolge zum erforderlichen Format und zurückkehren es als endgültige Ausgabe.
C++
   // C++ program to find the smallest d-digit    // number with the given sum using   // Greedy Technique   #include          using     namespace     std  ;   string     smallestNumber  (  int     s       int     d  )     {          // If sum is too small or too large       // for d digits      if     (  s      <     1     ||     s     >     9     *     d  )     {      return     '-1'  ;      }      string     result  (  d       '0'  );             // Reserve 1 for the leftmost digit      s  --  ;         // Fill digits from right to left      for     (  int     i     =     d     -     1  ;     i     >     0  ;     i  --  )     {          // Place the largest possible value  <= 9      if     (  s     >     9  )     {      result  [  i  ]     =     '9'  ;      s     -=     9  ;      }     else     {      result  [  i  ]     =     '0'     +     s  ;      s     =     0  ;      }      }      // Place the leftmost digit ensuring      // it's non-zero      result  [  0  ]     =     '1'     +     s  ;          return     result  ;   }   // Driver Code   int     main  ()     {          int     s     =     9       d     =     2  ;          cout      < <     smallestNumber  (  s       d  )      < <     endl  ;      return     0  ;   }   
Java
   // Java program to find the smallest d-digit    // number with the given sum using   // Greedy Technique   import     java.util.*  ;   class   GfG     {          static     String     smallestNumber  (  int     s       int     d  )     {          // If sum is too small or too large       // for d digits      if     (  s      <     1     ||     s     >     9     *     d  )     {      return     '-1'  ;      }      char  []     result     =     new     char  [  d  ]  ;      Arrays  .  fill  (  result       '0'  );          // Reserve 1 for the leftmost digit      s  --  ;      // Fill digits from right to left      for     (  int     i     =     d     -     1  ;     i     >     0  ;     i  --  )     {          // Place the largest possible value  <= 9      if     (  s     >     9  )     {      result  [  i  ]     =     '9'  ;      s     -=     9  ;      }     else     {      result  [  i  ]     =     (  char  )     (  '0'     +     s  );      s     =     0  ;      }      }      // Place the leftmost digit ensuring      // it's non-zero      result  [  0  ]     =     (  char  )     (  '1'     +     s  );          return     new     String  (  result  );      }      // Driver Code      public     static     void     main  (  String  []     args  )     {          int     s     =     9       d     =     2  ;          System  .  out  .  println  (  smallestNumber  (  s       d  ));      }   }   
Python
   # Python program to find the smallest d-digit    # number with the given sum using   # Greedy Technique   def   smallestNumber  (  s     d  ):   # If sum is too small or too large    # for d digits   if   s    <   1   or   s   >   9   *   d  :   return   '-1'   result   =   [  '0'  ]   *   d   # Reserve 1 for the leftmost digit   s   -=   1   # Fill digits from right to left   for   i   in   range  (  d   -   1     0     -  1  ):   # Place the largest possible value  <= 9   if   s   >   9  :   result  [  i  ]   =   '9'   s   -=   9   else  :   result  [  i  ]   =   str  (  s  )   s   =   0   # Place the leftmost digit ensuring   # it's non-zero   result  [  0  ]   =   str  (  1   +   s  )   return   ''  .  join  (  result  )   # Driver Code   if   __name__   ==   '__main__'  :   s     d   =   9     2   print  (  smallestNumber  (  s     d  ))   
C#
   // C# program to find the smallest d-digit    // number with the given sum using   // Greedy Technique   using     System  ;   class     GfG     {      static     string     smallestNumber  (  int     s       int     d  )     {          // If sum is too small or too large       // for d digits      if     (  s      <     1     ||     s     >     9     *     d  )     {      return     '-1'  ;      }      char  []     result     =     new     char  [  d  ];      Array  .  Fill  (  result       '0'  );      // Reserve 1 for the leftmost digit      s  --  ;      // Fill digits from right to left      for     (  int     i     =     d     -     1  ;     i     >     0  ;     i  --  )     {          // Place the largest possible value  <= 9      if     (  s     >     9  )     {      result  [  i  ]     =     '9'  ;      s     -=     9  ;      }     else     {      result  [  i  ]     =     (  char  )     (  '0'     +     s  );      s     =     0  ;      }      }      // Place the leftmost digit ensuring      // it's non-zero      result  [  0  ]     =     (  char  )     (  '1'     +     s  );          return     new     string  (  result  );      }      // Driver Code      static     void     Main  ()     {          int     s     =     9       d     =     2  ;          Console  .  WriteLine  (  smallestNumber  (  s       d  ));      }   }   
JavaScript
   // JavaScript program to find the smallest d-digit    // number with the given sum using   // Greedy Technique   function     smallestNumber  (  s       d  )     {          // If sum is too small or too large       // for d digits      if     (  s      <     1     ||     s     >     9     *     d  )     {      return     '-1'  ;      }      let     result     =     Array  (  d  ).  fill  (  '0'  );         // Reserve 1 for the leftmost digit      s  --  ;      // Fill digits from right to left      for     (  let     i     =     d     -     1  ;     i     >     0  ;     i  --  )     {          // Place the largest possible value  <= 9      if     (  s     >     9  )     {      result  [  i  ]     =     '9'  ;      s     -=     9  ;      }     else     {      result  [  i  ]     =     String  (  s  );      s     =     0  ;      }      }      // Place the leftmost digit ensuring      // it's non-zero      result  [  0  ]     =     String  (  1     +     s  );          return     result  .  join  (  ''  );   }   // Driver Code   let     s     =     9       d     =     2  ;   console  .  log  (  smallestNumber  (  s       d  ));   

Ausgabe
18