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 firstname.lastname@example.org. 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
- Calculate the Discriminant Value
- Check if all digits of a number divide it
- Count ways to reach the n’th stair
- Compute sum of digits in all numbers from 1 to n
- Number of Permutations such that no Three Terms forms Increasing Subsequence
- Check if the first and last digit of the smallest number forms a prime
- Print all substring of a number without any conversion
- Complement of a number with any base b
- Check if Decimal representation of an Octal number is divisible by 7