The problem is to check whether the decimal representation of the given binary number is divisible by 5 or not. Take care, the number could be very large and may not fit even in long long int. The approach should be such that there are zero or minimum number of multiplication and division operations. No leading 0’s are there in the input.
Input : 1010 Output : YES (1010)2 = (10)10, and 10 is divisible by 5. Input : 10000101001 Output : YES
Approach: The following steps are:
- Convert the binary number to base 4.
- Numbers in base 4 contains only 0, 1, 2, 3 as their digits.
- 5 in base 4 is equivalent to 11.
- Now apply the rule of divisibility by 11 where you add all the digits at odd places and add all the digits at even places and then subtract one from the other. If the result is divisible by 11(which remember is 5), then the binary number is divisible by 5.
How to convert binary number to base 4 representation?
- Check whether the length of binary string is even or odd.
- If odd, the add ‘0’ in the beginning of the string.
- Now, traverse the string from left to right.
- One by extract substrings of size 2 and add their equivalent decimal to the resultant string.
Time Complexity: O(n), where n is the number of digits in the binary number.
This article is contributed by Ayush Jauhari. 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.
- Decimal representation of given binary string is divisible by 10 or not
- Decimal representation of given binary string is divisible by 20 or not
- Sum of decimal equivalent of all possible pairs of Binary representation of a Number
- Construct Binary Tree from String with bracket representation
- Counting even decimal value substrings in a binary string
- Number of substrings with odd decimal value in a binary string
- Largest sub-string of a binary string divisible by 2
- Number of sub-strings in a given binary string divisible by 2
- Number of subsequences in a given binary string divisible by 2
- Longest sub-sequence of a binary string divisible by 3
- Number of sub-sequences of non-zero length of a binary string divisible by 3
- Minimum swaps required to make a binary string divisible by 2^k
- Find the occurrence of the given binary pattern in the binary representation of the array elements
- Binary representation of next number
- Maximum 0's between two immediate 1's in binary representation