Check divisibility of binary string by 2^k
Last Updated :
29 Sep, 2023
Given a binary string and a number k, the task is to check whether the binary string is evenly divisible by 2k or not.
Examples :
Input : 11000 k = 2
Output : Yes
Explanation :
(11000)2 = (24)10
24 is evenly divisible by 2k i.e. 4.
Input : 10101 k = 3
Output : No
Explanation :
(10101)2 = (21)10
21 is not evenly divisible by 2k i.e. 8.
Naive Approach: Compute the binary string into decimal and then simply check whether it is divisible by 2k. But, this approach is not feasible for the long binary strings as time complexity will be high for computing decimal number from binary string and then dividing it by 2k.
Step-by-step approach:
- Convert the binary string to decimal by iterating over each digit from left to right.
- Calculate the value of 2^k using bitwise left shift operation (1 << k).
- Check if the decimal value obtained in step 1 is divisible by the value obtained in step 2 using the modulus operator.
- If the modulus is zero, return true, otherwise return false.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// function to check whether
// given binary number is
// evenly divisible by 2^k or not
bool isDivisible(char str[], int k)
{
// convert binary string to decimal
int decimal_num = 0;
int base = 1;
int n = strlen(str);
for (int i = n - 1; i >= 0; i--) {
if (str[i] == '1') {
decimal_num += base;
}
base *= 2;
}
// check if decimal_num is divisible by 2^k
return (decimal_num % (1 << k)) == 0;
}
// Driver program to test above
int main()
{
// first example
char str1[] = "10101100";
int k = 2;
if (isDivisible(str1, k))
cout << "Yes" << endl;
else
cout << "No" << "\n";
// Second example
char str2[] = "111010100";
k = 2;
if (isDivisible(str2, k))
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
Java
import java.util.Arrays;
public class Main {
// function to check whether
// given binary number is
// evenly divisible by 2^k or not
public static boolean isDivisible(String str, int k) {
// convert binary string to decimal
int decimal_num = 0;
int base = 1;
int n = str.length();
for (int i = n - 1; i >= 0; i--) {
if (str.charAt(i) == '1') {
decimal_num += base;
}
base *= 2;
}
// check if decimal_num is divisible by 2^k
return (decimal_num % (1 << k)) == 0;
}
// Driver program to test above
public static void main(String[] args) {
// first example
String str1 = "10101100";
int k = 2;
if (isDivisible(str1, k))
System.out.println("Yes");
else
System.out.println("No");
// Second example
String str2 = "111010100";
k = 2;
if (isDivisible(str2, k))
System.out.println("Yes");
else
System.out.println("No");
}
}
Python3
# function to check whether
# given binary number is
# evenly divisible by 2^k or not
def is_divisible(binary_str, k):
# convert binary string to decimal
decimal_num = 0
base = 1
n = len(binary_str)
for i in range(n - 1, -1, -1):
if binary_str[i] == '1':
decimal_num += base
base *= 2
# check if decimal_num is divisible by 2^k
return decimal_num % (1 << k) == 0
# Driver program to test above
if __name__ == "__main__":
# first example
str1 = "10101100"
k = 2
if is_divisible(str1, k):
print("Yes")
else:
print("No")
# Second example
str2 = "111010100"
k = 2
if is_divisible(str2, k):
print("Yes")
else:
print("No")
# This code is contributed by shivamgupta0987654321
C#
using System;
class GFG
{
// function to check whether
// given binary number is
// evenly divisible by 2^k or not
static bool IsDivisible(string binaryStr, int k)
{
// convert binary string to decimal
int decimalNum = 0;
int baseValue = 1;
int n = binaryStr.Length;
for (int i = n - 1; i >= 0; i--)
{
if (binaryStr[i] == '1')
{
decimalNum += baseValue;
}
baseValue *= 2;
}
// check if decimalNum is divisible by 2^k
return (decimalNum % (1 << k)) == 0;
}
// Driver program to test above
static void Main()
{
// first example
string str1 = "10101100";
int k = 2;
if (IsDivisible(str1, k))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
// Second example
string str2 = "111010100";
k = 2;
if (IsDivisible(str2, k))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
JavaScript
// Javascript code
// Function to check whether the given binary number is evenly divisible by 2^k or not
function isDivisible(binaryStr, k) {
// Convert binary string to decimal
let decimalNum = 0;
let base = 1;
for (let i = binaryStr.length - 1; i >= 0; i--) {
if (binaryStr[i] === '1') {
decimalNum += base;
}
base *= 2;
}
// Check if decimalNum is divisible by 2^k
return decimalNum % (1 << k) === 0;
}
// Driver program to test above
const str1 = "10101100";
let k = 2;
if (isDivisible(str1, k)) {
console.log("Yes");
} else {
console.log("No");
}
const str2 = "111010100";
k = 2;
if (isDivisible(str2, k)) {
console.log("Yes");
} else {
console.log("No");
}
// This code is contributed by guptapratik
Time Complexity: O(n), where n is the length of the binary string.
Auxiliary Space: O(1), as we are not using any extra space.
Efficient Approach: In the binary string, check for the last k bits. If all the last k bits are 0, then the binary number is evenly divisible by 2k else it is not evenly divisible. Time complexity using this approach is O(k).
Below is the implementation of the approach.
C++
// C++ implementation to check whether
// given binary number is evenly
// divisible by 2^k or not
#include <bits/stdc++.h>
using namespace std;
// function to check whether
// given binary number is
// evenly divisible by 2^k or not
bool isDivisible(char str[], int k)
{
int n = strlen(str);
int c = 0;
// count of number of 0 from last
for (int i = 0; i < k; i++)
if (str[n - i - 1] == '0')
c++;
// if count = k, number is evenly
// divisible, so returns true else
// false
return (c == k);
}
// Driver program to test above
int main()
{
// first example
char str1[] = "10101100";
int k = 2;
if (isDivisible(str1, k))
cout << "Yes" << endl;
else
cout << "No"
<< "\n";
// Second example
char str2[] = "111010100";
k = 2;
if (isDivisible(str2, k))
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
Java
// Java implementation to check whether
// given binary number is evenly
// divisible by 2^k or not
class GFG {
// function to check whether
// given binary number is
// evenly divisible by 2^k or not
static boolean isDivisible(String str, int k)
{
int n = str.length();
int c = 0;
// count of number of 0 from last
for (int i = 0; i < k; i++)
if (str.charAt(n - i - 1) == '0')
c++;
// if count = k, number is evenly
// divisible, so returns true else
// false
return (c == k);
}
// Driver program to test above
public static void main(String args[])
{
// first example
String str1 = "10101100";
int k = 2;
if (isDivisible(str1, k) == true)
System.out.println("Yes");
else
System.out.println("No");
// Second example
String str2 = "111010100";
k = 2;
if (isDivisible(str2, k) == true)
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by JaideepPyne.
Python3
# Python 3 implementation to check
# whether given binary number is
# evenly divisible by 2^k or not
# function to check whether
# given binary number is
# evenly divisible by 2^k or not
def isDivisible(str, k):
n = len(str)
c = 0
# count of number of 0 from last
for i in range(0, k):
if (str[n - i - 1] == '0'):
c += 1
# if count = k, number is evenly
# divisible, so returns true else
# false
return (c == k)
# Driver program to test above
# first example
str1 = "10101100"
k = 2
if (isDivisible(str1, k)):
print("Yes")
else:
print("No")
# Second example
str2 = "111010100"
k = 2
if (isDivisible(str2, k)):
print("Yes")
else:
print("No")
# This code is contributed by Smitha
C#
// C# implementation to check whether
// given binary number is evenly
// divisible by 2^k or not
using System;
class GFG {
// function to check whether
// given binary number is
// evenly divisible by 2^k or not
static bool isDivisible(String str, int k)
{
int n = str.Length;
int c = 0;
// count of number of 0 from last
for (int i = 0; i < k; i++)
if (str[n - i - 1] == '0')
c++;
// if count = k, number is evenly
// divisible, so returns true else
// false
return (c == k);
}
// Driver program to test above
public static void Main()
{
// first example
String str1 = "10101100";
int k = 2;
if (isDivisible(str1, k) == true)
Console.Write("Yes\n");
else
Console.Write("No");
// Second example
String str2 = "111010100";
k = 2;
if (isDivisible(str2, k) == true)
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by Smitha.
JavaScript
<script>
// Javascript implementation to check whether
// given binary number is evenly
// divisible by 2^k or not
// Function to check whether
// given binary number is
// evenly divisible by 2^k or not
function isDivisible(str, k)
{
let n = str.length;
let c = 0;
// Count of number of 0 from last
for(let i = 0; i < k; i++)
if (str[n - i - 1] == '0')
c++;
// If count = k, number is evenly
// divisible, so returns true else
// false
return (c == k);
}
// Driver code
// First example
let str1 = "10101100";
let k = 2;
if (isDivisible(str1, k) == true)
document.write("Yes" + "</br>");
else
document.write("No");
// Second example
let str2 = "111010100";
k = 2;
if (isDivisible(str2, k) == true)
document.write("Yes");
else
document.write("No");
// This code is contributed by rameshtravel07
</script>
PHP
<?php
// PHP implementation to check whether
// given binary number is evenly
// function to check whether
// given binary number is
// evenly divisible by 2^k or not
function isDivisible($str, $k)
{
$n = strlen($str);
$c = 0;
// count of number
// of 0 from last
for ($i = 0; $i < $k; $i++)
if ($str[$n - $i - 1] == '0')
$c++;
// if count = k,
// number is evenly
// divisible, so
// returns true else
// false
return ($c == $k);
}
// Driver Code
// first example
$str1 = "10101100";
$k = 2;
if (isDivisible($str1, $k))
echo "Yes", "\n";
else
echo "No", "\n";
// Second example
$str2= "111010100";
$k = 2;
if (isDivisible($str2, $k))
echo "Yes", "\n";
else
echo "No", "\n";
// This code is contributed by Ajit
?>
Complexity Analysis:
- Time Complexity: O(k)
- Auxiliary Space: O(1)
Similar Reads
Check divisibility in a binary stream
Stream of binary number is coming, the task is to tell the number formed so far is divisible by a given number n. At any given time, you will get 0 or 1 and tell whether the number formed with these bits is divisible by n or not. Generally, e-commerce companies ask this type of questions. It was ask
11 min read
Check if a large number is divisibility by 15
Given a very large number. Check its divisibility by 15. Examples: Input: "31"Output: NoInput : num = "156457463274623847239840239 402394085458848462385346236 482374823647643742374523747 264723762374620"Output: YesGiven number is divisible by 15A number is divisible by 15 if it is divisible by 5 (if
5 min read
To check divisibility of any large number by 999
You are given an n-digit large number, you have to check whether it is divisible by 999 without dividing or finding modulo of number by 999. Examples: Input : 235764 Output : Yes Input : 23576 Output : No Since input number may be very large, we cannot use n % 999 to check if a number is divisible b
15 min read
Largest sub-string of a binary string divisible by 2
Given binary string str of length N, the task is to find the longest sub-string divisible by 2. If no such sub-string exists then print -1. Examples: Input: str = "11100011" Output: 111000 Largest sub-string divisible by 2 is "111000".Input: str = "1111" Output: -1 There is no sub-string of the give
3 min read
Check for Binary String
Given a string s, the task is to check if it is a binary string or not. A binary string is a string which only contains the characters '0' and '1'.Examples:Input: s = "01010101010"Output: trueInput: s = "geeks101"Output: false Approach:The idea is to iterate over all the characters of the string and
3 min read
Check if decimal representation of Binary String is divisible by 9 or not
Given a binary string S of length N, the task is to check if the decimal representation of the binary string is divisible by 9 or not. Examples: Input: S = 1010001Output:YesExplanation: The decimal representation of the binary string S is 81, which is divisible by 9. Therefore, the required output i
12 min read
Check if a large number is divisible by 20
Given a number, the task is to check if number is divisible by 20. The input number may be large and it may not be possible to store long long int and it may be very large number then we use the string.Examples: Input : 7575680 Output : Yes Input : 987985865687690 Output : No A number is divisible b
6 min read
Number of sub-strings in a given binary string divisible by 2
Given binary string str of length N, the task is to find the count of substrings of str which are divisible by 2. Leading zeros in a substring are allowed. Examples: Input: str = "101" Output: 2 "0" and "10" are the only substrings which are divisible by 2. Input: str = "10010" Output: 10 Naive appr
4 min read
Number of subsequences in a given binary string divisible by 2
Given binary string str of length N, the task is to find the count of subsequences of str which are divisible by 2. Leading zeros in a sub-sequence are allowed. Examples: Input: str = "101" Output: 2 "0" and "10" are the only subsequences which are divisible by 2.Input: str = "10010" Output: 22 Naiv
4 min read
Decimal representation of given binary string is divisible by 20 or not
The problem is to check whether the decimal representation of the given binary number is divisible by 20 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 the minimum numbers of multiplication and division oper
14 min read