Sort the numbers according to their sum of digits in C++

C++Server Side ProgrammingProgramming

In this section we will see how to sort numbers according to their sum of digits. So if a number has lesser sum of digits, then that will be placed at first, then next number will be placed with larger sum of digits.

data = {14, 129, 501, 23, 0, 145}

after sorting, they will be −

data = {0, 14, 23, 501, 145, 129}

Here we will create our own comparison logic to sort them. That comparison logic will be used in the sort function in C++ STL.

Algorithm

compare(num1, num2):
Begin
   if sum of digits of num1 < sum of digits of num2, then
      return 1
   return 0
End

Example

 Live Demo

#include<iostream>
#include<algorithm>
using namespace std;
int sumOfDigits(int n){
   int sum = 0;
   while(n){
      sum += n%10;
      n /= 10;
   }
   return sum;
}
int compare(int num1, int num2){
   if(sumOfDigits(num1) < sumOfDigits(num2))
   return 1;
   return 0;
}
main(){
   int data[] = {14, 129, 501, 23, 0, 145};
   int n = sizeof(data)/sizeof(data[0]);
   sort(data, data + n, compare);
   for(int i = 0; i<n; i++){
      cout << data[i] << " ";
   }
}

Output

0 14 23 501 145 129
raja
Published on 25-Sep-2019 11:58:25
Advertisements