# Minimum removals in a number to be divisible by 10 power raised to K 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

## Problem statement

Given two positive integers N and K. Find the minimum number of digits that can be removed from the number N such that after removals the number is divisible by 10K. Print -1 if it is impossible.

## Example

If N = 10203027 and K = 2 then we have to remove 3 digits. If we remove 3, 2 and 7 then number become 10200 which is divisible by 102

## Algorithm

1. Start traversing number from end. If the current digit is not zero, increment the counter variable, otherwise decrement variable K
2. If K is zero, then return counter as answer
3. After traversing the whole number, check if the current value of K is zero or not. If it is zero, return counter as answer, otherwise return answer as number of digits in N –1
4. If the given number does not contain any zero, return -1 as answer

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int getBitsToBeRemoved(int n, int k) {
string s = to_string(n);
int result = 0;
int zeroFound = 0;
for (int i = s.size() - 1; i >= 0; --i) {
if (k == 0) {
return result;
}
if (s[i] == '0') {
zeroFound = 1;
--k;
} else {
++result;
}
}
if (!k) {
return result;
} else if (zeroFound) {
return s.size() - 1;
}
return - 1;
}
int main() {
int n = 10203027;
int k = 2;
cout << "Minimum required removals = " <<
getBitsToBeRemoved(n, k) << endl;
return 0;
}

When you compile and execute above program. It generates following output

## Output

Minimum required removals = 3