📜  根据数字的总和对数字进行排序

📅  最后修改于: 2021-04-29 05:03:29             🧑  作者: Mango

给定N个非负整数的数组arr [] ,任务是根据这些整数的和对这些整数进行排序。

例子:

方法:想法是将每个元素及其位数之和存储在向量对中,然后根据所存储的位数之和对向量的所有元素进行排序。最后,按顺序打印元素。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the sum
// of the digits of n
int sumOfDigit(int n)
{
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n = n / 10;
    }
    return sum;
}
  
// Function to sort the array according to
// the sum of the digits of elements
void sortArr(int arr[], int n)
{
    // Vector to store digit sum with respective element
    vector > vp;
  
    // Inserting digit sum with element in the vector pair
    for (int i = 0; i < n; i++) {
        vp.push_back(make_pair(sumOfDigit(arr[i]), arr[i]));
    }
  
    // Quick sort the vector, this will sort the pair
    // according to sum of the digits of elements
    sort(vp.begin(), vp.end());
  
    // Print the sorted vector content
    for (int i = 0; i < vp.size(); i++)
        cout << vp[i].second << " ";
}
  
// Driver code
int main()
{
    int arr[] = { 14, 1101, 10, 35, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    sortArr(arr, n);
  
    return 0;
}


Python3
# Python3 implementation of the approach 
  
# Function to return the sum 
# of the digits of n 
def sumOfDigit(n) : 
      
    sum = 0; 
    while (n > 0) :
          
        sum += n % 10; 
        n = n // 10; 
          
    return sum; 
  
# Function to sort the array according to 
# the sum of the digits of elements 
def sortArr(arr, n) :
      
    # Vector to store digit sum with 
    # respective element 
    vp = []; 
  
    # Inserting digit sum with element
    # in the vector pair 
    for i in range(n) :
        vp.append([sumOfDigit(arr[i]), arr[i]]); 
  
    # Quick sort the vector, this will 
    # sort the pair according to sum 
    # of the digits of elements 
    vp.sort()
  
    # Print the sorted vector content 
    for i in range(len(vp)) :
        print(vp[i][1], end = " "); 
  
# Driver code 
if __name__ == "__main__" : 
  
    arr = [14, 1101, 10, 35, 0]; 
    n = len(arr);
    sortArr(arr, n); 
  
# This code is contributed by Ryuga


输出:
0 10 1101 14 35