bogdanNiculeasa

Sortare numere dupa suma cifrelor

Feb 15th, 2023
853
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int suma_cifrelor(int n);
  6.  
  7. int main()
  8. {
  9.     int n;
  10.     cin >> n;
  11.     int numere[n];
  12.     for (int i = 0; i < n; i++) {
  13.         cin >> numere[i];
  14.     }
  15.  
  16.     for (int i = 0; i < n; i++) {
  17.         for (int j = 0; j < n-1; j++) {
  18.             int sumaPozitieCurenta = suma_cifrelor(numere[j]);
  19.             int sumaPozitieViitoare = suma_cifrelor(numere[j+1]);
  20.             if ( sumaPozitieCurenta > sumaPozitieViitoare) {
  21.                 int aux = numere[j];
  22.                 numere[j] = numere[j+1];
  23.                 numere[j+1] = aux;
  24.             } else if (sumaPozitieCurenta == sumaPozitieViitoare) {
  25.                 if (numere[j] > numere[j+1]) {
  26.                     int aux = numere[j];
  27.                     numere[j] = numere[j+1];
  28.                     numere[j+1] = aux;
  29.                 }
  30.             }
  31.         }
  32.     }
  33.  
  34.     for (int i = 0; i < n; i++) {
  35.         cout << numere[i] << " ";
  36.     }
  37.  
  38.     return 0;
  39. }
  40.  
  41. int suma_cifrelor(int n) {
  42.     int suma = 0;
  43.     while (n > 0) {
  44.         suma += n % 10;
  45.         n = n / 10;
  46.     }
  47.     return suma;
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment