# Convert a number of length N such that it contains any one digit at least 'K' times in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In this tutorial, we will be discussing a program to convert a number of length N such that it contains any one digit at least ‘K’ times.

For this we will be provided with a number of given length N. Our task is to convert the digits in the given number such that any one digit gets repeated at least ‘K’ times. Also, you have to calculate the cost of this operation which is the absolute difference between the two and finally print the minimum cost.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
//calculating the minimum value and final number
int get_final(int n, int k, string a){
int modtemp;
//count of numbers changed to k
int co;
string temp;
//storing the minimum cost
pair<int, string> ans = make_pair(INT_MAX, "");
for (int i = 0; i < 10; i++) {
temp = a;
//storing the temporary modified number
modtemp = 0;
co = count(a.begin(), a.end(), i + '0');
for (int j = 1; j < 10; j++) {
if (i + j < 10) {
for (int p = 0; p < n; p++) {
if (co <= k)
break;
if (i + '0' == temp[p] - j) {
temp[p] = i + '0';
modtemp += j;
co++;
}
}
}
if (i - j >= 0) {
for (int p = n - 1; p >= 0; p--) {
if (co >= k)
break;
if (i + '0' == temp[p] + j) {
temp[p] = i + '0';
modtemp += j;
co++;
}
}
}
}
//replacing the minimum cost with the previous one
ans = min(ans, make_pair(modtemp, temp));
}
cout << ans.first << endl << ans.second << endl;
}
int main(){
int n = 5, k = 4;
string a = "21122";
get_final(n, k, a);
return 0;
}

## Output

1
21222