Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort the numbers according to their sum of digits in C++
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
#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
Advertisements