Write a code in c++ that transformed  a numbers into maximum numbers? for example if you are given a number 1214678 the the output of your program should be 8764211.

Solution with O(N) complexity

  1. Create an array of length 10, int arr[10]
  2. convert the number into single digits. “1214678” { 1,2,1,4,6,7,8}
  3. update the frequency of digit in arr. 

          arr[]  0 1 2 3 4 5 6 7 8 9

           freq 0  2 1 0 1 0 1 1 1 0

  1. print the array index from last to first. during printing repeat the index according to its frequency. if frequency is 0 do not print. for example if we print arr[] index from last to first , as we can see, 9th index has 0 frequency so it will not be printed. same as 8th index is having frequency 1 , then 8 will be printed. Note: look at the first index , its frequency is 2 so 1 will be printed 2 times.

Here is c implementation of above logic:

#include<stdio.h>
#include<string.h>

#define N 10

int convert(int num);
int arr[N];

int convert_arr_into_unmber(int arr[N]);

int main() {
	int num = 1214678;
	// init arr to 0
	memset(arr, 0, sizeof(arr));

	convert(num);
	return 0;
}

int convert(int num) {
	int last_digit = 0;

	if (num == 0)
		return 0;

	while (num) {
		last_digit = num % 10;

		// increment the frequency of last_digit in arr
		arr[last_digit]++;

		num = num / 10;
	}
	convert_arr_into_unmber(arr);
}

int convert_arr_into_unmber(int arr[N]) {
	int i = 0;
	int j = 0;
	int frequency_of_i;

	for (i = 9; i >= 0; i--) {
		if (arr[i]) {
			while (arr[i]--)
				printf("%d", i);
		}
	}
	printf("\n");
}

 



Related Contents to follow