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 (See this for details).
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.
Time Complexity: O(n) where n is the length of the number.
This article is contributed by Striver. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Print digit's position to be removed to make a number divisible by 6
- Possible to make a divisible by 3 number using all digits in an array
- Minimum number of digits to be removed so that no two consecutive digits are same
- Minimum number of elements to be removed to make XOR maximum
- Minimum number of characters to be removed to make a binary string alternate
- Find N digits number which is divisible by D
- Largest number with the given set of N digits that is divisible by 2, 3 and 5
- Smallest number with sum of digits as N and divisible by 10^N
- Check whether sum of digits at odd places of a number is divisible by K
- Minimum digits to remove to make a number Perfect Square
- Given a large number, check if a subsequence of digits is divisible by 8
- Check whether product of digits at even places of a number is divisible by K
- Find the number of boxes to be removed
- Find the Largest number with given number of digits and sum of digits
- Find smallest number with given number of digits and sum of digits