Given a very large number num (1 <= num <= 10^1000), print the number of digits that needs to be removed to make the number exactly divisible by 3. If it is not possible then print -1.
Input: num = "1234" Output: 1 Explanation: we need to remove one digit that is 1 or 4, to make the number divisible by 3.on Input: num = "11" Output: -1 Explanation: It is not possible to remove any digits and make it divisible by 3.
The idea is based on the fact that a number is multiple of 3 if and only if sum of its digits is multiple of 3 .
One important observation used here is that the answer is at-most 2 if answer exists. So here are the only options for the function:
- Sum of digits is already equal to 0 modulo 3. Thus we don’t have to erase any digits.
- There exists such a digit that equals sum modulo 3. Then we just have to erase a single digits
- All of the digits are neither divisible by 3, nor equal to sum modulo 3. So two of such digits will sum up to number, which equals sum modulo 3, (2+2) mod 3=1, (1+1) mod 3=2.
// CPP program to find the minimum number of
// digits to be removed to make a large number
// divisible by 3.
// function to count the no of removal of digits
// to make a very large number divisible by 3
n = num.length();
// add up all the digits of num
sum = accumulate(begin(num), end(num), 0) -
// if num is already is divisible by 3
// then no digits are to be removed
(sum % 3 == 0)
// if there is single digit, then it is
// not possible to remove one digit.
(n == 1)
// traverse through the number and find out
// if any number on removal makes the sum
// divisible by 3
i = 0; i < n; i++)
(sum % 3 == (num[i] -
) % 3)
// if there are two numbers then it is
// not possible to remove two digits.
(n == 2)
// Otherwise we can always make a number
// multiple of 2 by removing 2 digits.
// driver program to test the above function
string num =
cout << divisible(num);
Time Complexity: O(n) where n is the length of the number.
Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/number-digits-removed-make-number-divisible-3/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at
http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements