

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Questions & Answers
- Python – Sort List items on the basis of their Digits
- Python – Sort List items on basis of their Digits
- Python program to Sort a List of Dictionaries by the Sum of their Values
- Sort array according to the date property of the objects JavaScript
- Compute sum of digits in all numbers from 1 to n
- Count of n digit numbers whose sum of digits equals to given sum in C++
- Sorting according to weights of numbers in JavaScript
- Find numbers whose sum of digits equals a value
- Print numbers with digits 0 and 1 only such that their sum is N in C Program.
- Sort a list according to the Length of the Elements in Python program
- Python program to sort a List according to the Length of the Elements?
- What are different types of computers according to their size in C?
- Print all n-digit numbers whose sum of digits equals to given sum in C++
- Sort the second array according to the elements of the first array in JavaScript
- Sorting numbers according to the digit root JavaScript
Advertisements