text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Count Set | Recursive function to find number of set bist in a number ; Base condition ; If Least significant bit is set ; If Least significant bit is not set ; Driver code ; Function call
def CountSetBits ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( ( n & 1 ) == 1 ) : NEW_LINE INDENT return 1 + CountSetBits ( n >> 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return CountSetBits ( n >> 1 ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 21 ; NEW_LINE print ( CountSetBits ( n ) ) ; NEW_LINE DEDENT
Count smaller elements on right side and greater elements on left side using Binary Index Tree | Python3 implementation of the approach ; Function to return the sum of arr [ 0. . index ] This function assumes that the array is preprocessed and partial sums of array elements are stored in BITree [ ] ; Initialize result ; Traverse ancestors of BITree [ index ] ; Add current element of BITree to sum ; Move index to parent node in getSum View ; Updates a node in Binary Index Tree ( BITree ) at given index in BITree . The given value ' val ' is added to BITree [ i ] and all of its ancestors in tree . ; Traverse all ancestors and add 'val ; Add ' val ' to current node of BI Tree ; Update index to that of parent in update View ; Converts an array to an array with values from 1 to n and relative order of smaller and greater elements remains same . For example , { 7 , - 90 , 100 , 1 } is converted to { 3 , 1 , 4 , 2 } ; Create a copy of arrp [ ] in temp and sort the temp array in increasing order ; Traverse all array elements ; lower_bound ( ) Returns pointer to the first element greater than or equal to arr [ i ] ; Function to find smaller_right array ; Convert arr [ ] to an array with values from 1 to n and relative order of smaller and greater elements remains same . For example , { 7 , - 90 , 100 , 1 } is converted to { 3 , 1 , 4 , 2 } ; Create a BIT with size equal to maxElement + 1 ( Extra one is used so that elements can be directly be used as index ) ; To store smaller elements in right side and greater elements on left side ; Traverse all elements from right . ; Get count of elements smaller than arr [ i ] ; Add current element to BIT ; Print smaller_right array ; Find all left side greater elements ; Get count of elements greater than arr [ i ] ; Add current element to BIT ; Print greater_left array ; Driver Code ; Function call
from bisect import bisect_left as lower_bound NEW_LINE def getSum ( BITree , index ) : NEW_LINE INDENT s = 0 NEW_LINE while index > 0 : NEW_LINE INDENT s += BITree [ index ] NEW_LINE index -= index & ( - index ) NEW_LINE DEDENT return s NEW_LINE DEDENT def updateBIT ( BITree , n , index , val ) : NEW_LINE ' NEW_LINE INDENT while index <= n : NEW_LINE INDENT BITree [ index ] += val NEW_LINE index += index & ( - index ) NEW_LINE DEDENT DEDENT def convert ( arr , n ) : NEW_LINE INDENT temp = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp [ i ] = arr [ i ] NEW_LINE DEDENT temp . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = lower_bound ( temp , arr [ i ] ) + 1 NEW_LINE DEDENT DEDENT def findElements ( arr , n ) : NEW_LINE INDENT convert ( arr , n ) NEW_LINE BIT = [ 0 ] * ( n + 1 ) NEW_LINE smaller_right = [ 0 ] * n NEW_LINE greater_left = [ 0 ] * n NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT smaller_right [ i ] = getSum ( BIT , arr [ i ] - 1 ) NEW_LINE updateBIT ( BIT , n , arr [ i ] , 1 ) NEW_LINE DEDENT print ( " Smaller ▁ right : " , end = " ▁ " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( smaller_right [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT BIT [ i ] = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT greater_left [ i ] = i - getSum ( BIT , arr [ i ] ) NEW_LINE updateBIT ( BIT , n , arr [ i ] , 1 ) NEW_LINE DEDENT print ( " Greater ▁ left : " , end = " ▁ " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( greater_left [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 12 , 1 , 2 , 3 , 0 , 11 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE findElements ( arr , n ) NEW_LINE DEDENT
Sum of Bitwise OR of all pairs in a given array | Returns value of " arr [ 0 ] ▁ | ▁ arr [ 1 ] ▁ + ▁ arr [ 0 ] ▁ | ▁ arr [ 2 ] ▁ + ▁ . . . ▁ arr [ i ] ▁ | ▁ arr [ j ] ▁ + ▁ . . . . . ▁ arr [ n - 2 ] ▁ | ▁ arr [ n - 1 ] " ; Consider all pairs ( arr [ i ] , arr [ j ) such that i < j ; Driver program to test above function
def pairORSum ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( ( i + 1 ) , n ) : NEW_LINE INDENT ans = ans + arr [ i ] | arr [ j ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( pairORSum ( arr , n ) ) NEW_LINE
Number of 0 s and 1 s at prime positions in the given array | Function that returns true if n is prime ; Check from 2 to n ; Function to find the count of 0 s and 1 s at prime indices ; To store the count of 0 s and 1 s ; If current 0 is at prime position ; If current 1 is at prime position ; Driver code
def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT for i in range ( 2 , n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def countPrimePosition ( arr ) : NEW_LINE INDENT c0 = 0 ; c1 = 0 ; NEW_LINE n = len ( arr ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == 0 and isPrime ( i ) ) : NEW_LINE INDENT c0 += 1 ; NEW_LINE DEDENT if ( arr [ i ] == 1 and isPrime ( i ) ) : NEW_LINE INDENT c1 += 1 ; NEW_LINE DEDENT DEDENT print ( " Number ▁ of ▁ 0s ▁ = " , c0 ) ; NEW_LINE print ( " Number ▁ of ▁ 1s ▁ = " , c1 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 0 , 1 , 0 , 1 ] ; NEW_LINE countPrimePosition ( arr ) ; NEW_LINE DEDENT
Find a sub matrix with maximum XOR | Python3 program to implement the above approach ; Compute the xor of elements from ( 1 , 1 ) to ( i , j ) and store it in prefix_xor [ i ] [ j ] ; xor of submatrix from 1 , 1 to i , j is ( xor of submatrix from 1 , 1 to i - 1 , j ) ^ ( xor of submatrix from 1 , 1 to i , j - 1 ) ^ ( xor of submatrix from 1 , 1 to i - 1 , j - 1 ) ^ arr [ i ] [ j ] ; find the submatrix with maximum xor value ; we need four loops to find all the submatrix of a matrix ; xor of submatrix from i , j to i1 , j1 is ( xor of submatrix from 1 , 1 to i1 , j1 ) ^ ( xor of submatrix from 1 , 1 to i - 1 , j - 1 ) ^ ( xor of submatrix from 1 , 1 to i1 , j - 1 ) ^ ( xor of submatrix from 1 , 1 to i - 1 , j1 ) ; if the xor is greater than maximum value substitute it ; Driver code ; Find the prefix_xor ; Find submatrix with maximum bitwise xor
N = 101 NEW_LINE def prefix ( arr , prefix_xor , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 1 , n ) : NEW_LINE INDENT prefix_xor [ i ] [ j ] = ( arr [ i ] [ j ] ^ prefix_xor [ i - 1 ] [ j ] ^ prefix_xor [ i ] [ j - 1 ] ^ prefix_xor [ i - 1 ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT def Max_xor ( prefix_xor , n ) : NEW_LINE INDENT max_value = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT for i1 in range ( i , n + 1 ) : NEW_LINE INDENT for j1 in range ( j , n + 1 ) : NEW_LINE INDENT x = 0 NEW_LINE x ^= prefix_xor [ i1 ] [ j1 ] NEW_LINE x ^= prefix_xor [ i - 1 ] [ j - 1 ] NEW_LINE x ^= prefix_xor [ i1 ] [ j - 1 ] NEW_LINE x ^= prefix_xor [ i - 1 ] [ j1 ] NEW_LINE max_value = max ( max_value , x ) NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( max_value ) NEW_LINE DEDENT arr = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] ] NEW_LINE n = 4 NEW_LINE prefix_xor = [ [ 0 for i in range ( N ) ] for i in range ( N ) ] NEW_LINE prefix ( arr , prefix_xor , n ) NEW_LINE Max_xor ( prefix_xor , n ) NEW_LINE
Multiply a number by 15 without using * and / operators | Function to return ( 15 * N ) without using ' * ' or ' / ' operator ; prod = 16 * n ; ( ( 16 * n ) - n ) = 15 * n ; Driver code
def multiplyByFifteen ( n ) : NEW_LINE INDENT prod = ( n << 4 ) NEW_LINE prod = prod - n NEW_LINE return prod NEW_LINE DEDENT n = 7 NEW_LINE print ( multiplyByFifteen ( n ) ) NEW_LINE
Multiply a number by 15 without using * and / operators | Function to perform Multiplication ; prod = 8 * n ; Add ( 4 * n ) ; Add ( 2 * n ) ; Add n ; ( 8 * n ) + ( 4 * n ) + ( 2 * n ) + n = ( 15 * n ) ; Driver code
def multiplyByFifteen ( n ) : NEW_LINE INDENT prod = ( n << 3 ) NEW_LINE prod += ( n << 2 ) NEW_LINE prod += ( n << 1 ) NEW_LINE prod += n NEW_LINE return prod NEW_LINE DEDENT n = 7 NEW_LINE print ( multiplyByFifteen ( n ) ) NEW_LINE
Game Theory in Balanced Ternary Numeral System | ( Moving 3 k steps at a time ) | Numbers are in range of pow ( 3 , 32 ) ; Conversion of ternary into balanced ternary as start iterating from Least Significant Bit ( i . e 0 th ) , if encountered 0 or 1 , safely skip and pass carry 0 further 2 , replace it to - 1 and pass carry 1 further 3 , replace it to 0 and pass carry 1 further ; Similar to binary conversion ; Driver code ; Moving on to first occupied bit ; Printing ; Print ' Z ' in place of - 1
arr = [ 0 ] * 32 NEW_LINE def balTernary ( ter ) : NEW_LINE INDENT carry , base , i = 0 , 10 , 31 NEW_LINE while ter > 0 : NEW_LINE INDENT rem = ( ter % base ) + carry NEW_LINE if rem == 0 : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE carry , i = 0 , i - 1 NEW_LINE DEDENT elif rem == 1 : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE carry , i = 0 , i - 1 NEW_LINE DEDENT elif rem == 2 : NEW_LINE INDENT arr [ i ] = - 1 NEW_LINE carry , i = 1 , i - 1 NEW_LINE DEDENT elif rem == 3 : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE carry , i = 1 , i - 1 NEW_LINE DEDENT ter = ter // base NEW_LINE DEDENT if carry == 1 : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT DEDENT def ternary ( number ) : NEW_LINE INDENT ans , rem , base = 0 , 1 , 1 NEW_LINE while number > 0 : NEW_LINE INDENT rem = number % 3 NEW_LINE ans = ans + rem * base NEW_LINE number //= 3 NEW_LINE base = base * 10 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT number = 3056 NEW_LINE ter = ternary ( number ) NEW_LINE balTernary ( ter ) NEW_LINE i = 0 NEW_LINE while arr [ i ] == 0 : NEW_LINE INDENT i += 1 NEW_LINE DEDENT for j in range ( i , 32 ) : NEW_LINE INDENT if arr [ j ] == - 1 : NEW_LINE INDENT print ( ' Z ' , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ j ] , end = " " ) NEW_LINE DEDENT DEDENT DEDENT
Minimum value among AND of elements of every subset of an array | Python program for the above approach ; Find AND of whole array ; Print the answer ; Driver code
def minAND ( arr , n ) : NEW_LINE INDENT s = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT s = s & arr [ i ] NEW_LINE DEDENT print ( s ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE minAND ( arr , n ) NEW_LINE
Modify a binary array to Bitwise AND of all elements as 1 | Function to check if it is possible or not ; Driver code
def check ( a , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 0 , 1 , 0 , 1 ] NEW_LINE n = len ( a ) NEW_LINE if ( check ( a , n ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT
Find array using different XORs of elements in groups of size 4 | Utility function to print the contents of the array ; Function to find the required array ; Print the array ; Driver code
def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def findArray ( q , n ) : NEW_LINE INDENT arr = [ None ] * n NEW_LINE k = 0 NEW_LINE for j in range ( int ( n / 4 ) ) : NEW_LINE INDENT ans = q [ k ] ^ q [ k + 3 ] NEW_LINE arr [ k + 1 ] = q [ k + 1 ] ^ ans NEW_LINE arr [ k + 2 ] = q [ k + 2 ] ^ ans NEW_LINE arr [ k ] = q [ k ] ^ ( ( arr [ k + 1 ] ) ^ ( arr [ k + 2 ] ) ) NEW_LINE arr [ k + 3 ] = q [ k + 3 ] ^ ( arr [ k + 1 ] ^ arr [ k + 2 ] ) NEW_LINE k += 4 NEW_LINE DEDENT printArray ( arr , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT q = [ 4 , 1 , 7 , 0 ] NEW_LINE n = len ( q ) NEW_LINE findArray ( q , n ) NEW_LINE DEDENT
Count of values of x <= n for which ( n XOR x ) = ( n | Function to return the count of valid values of x ; Convert n into binary String ; To store the count of 1 s ; If current bit is 1 ; Calculating answer ; Driver code
def countX ( n ) : NEW_LINE INDENT binary = " { 0 : b } " . format ( n ) NEW_LINE count = 0 NEW_LINE for i in range ( len ( binary ) ) : NEW_LINE INDENT if ( binary [ i ] == '1' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT answer = int ( pow ( 2 , count ) ) NEW_LINE return answer NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE answer = countX ( n ) NEW_LINE print ( answer ) NEW_LINE DEDENT
Check if the binary representation of a number has equal number of 0 s and 1 s in blocks | Function to convert decimal to binary ; Count same bits in last block ; If n is 0 or it has all 1 s , then it is not considered to have equal number of 0 s and 1 s in blocks . ; Count same bits in all remaining blocks . ; Driver Code
def isEqualBlock ( n ) : NEW_LINE INDENT first_bit = n % 2 NEW_LINE first_count = 1 NEW_LINE n = n // 2 NEW_LINE while n % 2 == first_bit and n > 0 : NEW_LINE INDENT n = n // 2 NEW_LINE first_count += 1 NEW_LINE DEDENT if n == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT while n > 0 : NEW_LINE INDENT first_bit = n % 2 NEW_LINE curr_count = 1 NEW_LINE n = n // 2 NEW_LINE while n % 2 == first_bit : NEW_LINE INDENT n = n // 2 NEW_LINE curr_count += 1 NEW_LINE DEDENT if curr_count != first_count : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 51 NEW_LINE if isEqualBlock ( n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
First and Last Three Bits | Python 3 implementation of the approach ; Function to print the first and last 3 bits equivalent decimal number ; Converting n to binary ; Length of the array has to be at least 3 ; Convert first three bits to decimal ; Print the decimal ; Convert last three bits to decimal ; Print the decimal ; Driver code
from math import pow NEW_LINE def binToDecimal3 ( n ) : NEW_LINE INDENT a = [ 0 for i in range ( 64 ) ] NEW_LINE x = 0 NEW_LINE i = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT a [ i ] = n % 2 NEW_LINE n = int ( n / 2 ) NEW_LINE i += 1 NEW_LINE DEDENT if ( i < 3 ) : NEW_LINE INDENT x = 3 NEW_LINE DEDENT else : NEW_LINE INDENT x = i NEW_LINE DEDENT d = 0 NEW_LINE p = 0 NEW_LINE for i in range ( x - 3 , x , 1 ) : NEW_LINE INDENT d += a [ i ] * pow ( 2 , p ) NEW_LINE p += 1 NEW_LINE DEDENT print ( int ( d ) , end = " ▁ " ) NEW_LINE d = 0 NEW_LINE p = 0 NEW_LINE for i in range ( 0 , 3 , 1 ) : NEW_LINE INDENT d += a [ i ] * pow ( 2 , p ) NEW_LINE p += 1 NEW_LINE DEDENT print ( int ( d ) , end = " ▁ " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 86 NEW_LINE binToDecimal3 ( n ) NEW_LINE DEDENT
First and Last Three Bits | Function to print the first and last 3 bits equivalent decimal number ; Number formed from last three bits ; Let us get first three bits in n ; Number formed from first three bits ; Printing result ; Driver code
def binToDecimal3 ( n ) : NEW_LINE INDENT last_3 = ( ( n & 4 ) + ( n & 2 ) + ( n & 1 ) ) ; NEW_LINE n = n >> 3 NEW_LINE while ( n > 7 ) : NEW_LINE INDENT n = n >> 1 NEW_LINE DEDENT first_3 = ( ( n & 4 ) + ( n & 2 ) + ( n & 1 ) ) NEW_LINE print ( first_3 , last_3 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 86 NEW_LINE binToDecimal3 ( n ) NEW_LINE DEDENT
Count of numbers which can be made power of 2 by given operation | Function that returns true if x is a power of 2 ; If x & ( x - 1 ) = 0 then x is a power of 2 ; Function to return the required count ; If a [ i ] or ( a [ i ] + 1 ) is a power of 2 ; Driver code
def isPowerOfTwo ( x ) : NEW_LINE INDENT if ( x == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( ( x & ( x - 1 ) ) == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def countNum ( a , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( isPowerOfTwo ( a [ i ] ) or isPowerOfTwo ( a [ i ] + 1 ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 6 , 9 , 3 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countNum ( arr , n ) ) NEW_LINE DEDENT
Sum of elements from an array having even parity | Function that returns true if x has even parity ; We basically count set bits https : www . geeksforgeeks . org / count - set - bits - in - an - integer / ; Function to return the sum of the elements from an array which have even parity ; If a [ i ] has even parity ; Driver code
def checkEvenParity ( x ) : NEW_LINE INDENT parity = 0 NEW_LINE while ( x != 0 ) : NEW_LINE INDENT x = x & ( x - 1 ) NEW_LINE parity += 1 NEW_LINE DEDENT if ( parity % 2 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def sumlist ( a , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( checkEvenParity ( a [ i ] ) ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 3 , 5 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( sumlist ( arr , n ) ) NEW_LINE DEDENT
Range Sum Queries and Update with Square Root | Python program to calculate sum in an interval and update with square root ; Maximum size of input array ; structure for queries with members type , leftIndex , rightIndex of the query ; function for updating the value ; function for calculating the required sum between two indexes ; function to return answer to queries ; Declaring a Set ; inserting indexes of those numbers which are greater than 1 ; update query ; find the left index of query in the set using binary search auto it = s . lower_bound ( que [ i ] . l ) ; ; if it crosses the right index of query or end of set , then break ; update the value of arr [ i ] to itss square root ; if updated value becomes equal to 1 remove it from the set ; increment the index ; sum query ; Driver Code ; input array using 1 - based indexing ; declaring array of structure of type queries ; answer the Queries
from typing import List NEW_LINE import bisect NEW_LINE from math import sqrt , floor NEW_LINE MAX = 100 NEW_LINE BIT = [ 0 for _ in range ( MAX + 1 ) ] NEW_LINE class queries : NEW_LINE INDENT def __init__ ( self , type : int = 0 , l : int = 0 , r : int = 0 ) -> None : NEW_LINE INDENT self . type = type NEW_LINE self . l = l NEW_LINE self . r = r NEW_LINE DEDENT DEDENT def update ( x : int , val : int , n : int ) -> None : NEW_LINE INDENT a = x NEW_LINE while a <= n : NEW_LINE INDENT BIT [ a ] += val NEW_LINE a += a & - a NEW_LINE DEDENT DEDENT def sum ( x : int ) -> int : NEW_LINE INDENT s = 0 NEW_LINE a = x NEW_LINE while a : NEW_LINE INDENT s += BIT [ a ] NEW_LINE a -= a & - a NEW_LINE DEDENT return s NEW_LINE DEDENT def answerQueries ( arr : List [ int ] , que : List [ queries ] , n : int , q : int ) -> None : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > 1 ) : NEW_LINE INDENT s . add ( i ) NEW_LINE DEDENT update ( i , arr [ i ] , n ) NEW_LINE DEDENT for i in range ( q ) : NEW_LINE INDENT if ( que [ i ] . type == 1 ) : NEW_LINE INDENT while True : NEW_LINE INDENT ss = list ( sorted ( s ) ) NEW_LINE it = bisect . bisect_left ( ss , que [ i ] . l ) NEW_LINE if it == len ( s ) or ss [ it ] > que [ i ] . r : NEW_LINE INDENT break NEW_LINE DEDENT que [ i ] . l = ss [ it ] NEW_LINE update ( ss [ it ] , floor ( sqrt ( arr [ ss [ it ] ] ) - arr [ ss [ it ] ] ) , n ) NEW_LINE arr [ ss [ it ] ] = floor ( sqrt ( arr [ ss [ it ] ] ) ) NEW_LINE if ( arr [ ss [ it ] ] == 1 ) : NEW_LINE INDENT s . remove ( ss [ it ] ) NEW_LINE DEDENT que [ i ] . l += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( sum ( que [ i ] . r ) - sum ( que [ i ] . l - 1 ) ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT q = 4 NEW_LINE arr = [ 0 , 4 , 5 , 1 , 2 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE que = [ queries ( ) for _ in range ( q + 1 ) ] NEW_LINE que [ 0 ] . type , que [ 0 ] . l , que [ 0 ] . r = 2 , 1 , 5 NEW_LINE que [ 1 ] . type , que [ 1 ] . l , que [ 1 ] . r = 1 , 1 , 2 NEW_LINE que [ 2 ] . type , que [ 2 ] . l , que [ 2 ] . r = 1 , 2 , 4 NEW_LINE que [ 3 ] . type , que [ 3 ] . l , que [ 3 ] . r = 2 , 1 , 5 NEW_LINE answerQueries ( arr , que , n , q ) NEW_LINE DEDENT
Number of pairs with Bitwise OR as Odd number | Function to count pairs with odd OR ; find OR operation check odd or odd ; return count of odd pair ; Driver Code
def findOddPair ( A , N ) : NEW_LINE INDENT oddPair = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( ( A [ i ] A [ j ] ) % 2 != 0 ) : NEW_LINE INDENT oddPair += 1 NEW_LINE DEDENT DEDENT DEDENT return oddPair NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT A = [ 5 , 6 , 2 , 8 ] NEW_LINE N = len ( A ) NEW_LINE print ( findOddPair ( A , N ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT
Count pairs with Bitwise XOR as EVEN number | Function to count number of even pairs ; variable for counting even pairs ; find all pairs ; find XOR operation check even or even ; return number of even pair ; Driver Code ; calling function findevenPair and prnumber of even pair
def findevenPair ( A , N ) : NEW_LINE INDENT evenPair = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( ( A [ i ] ^ A [ j ] ) % 2 == 0 ) : NEW_LINE INDENT evenPair += 1 NEW_LINE DEDENT DEDENT DEDENT return evenPair ; NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT A = [ 5 , 4 , 7 , 2 , 1 ] NEW_LINE N = len ( A ) NEW_LINE print ( findevenPair ( A , N ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT
Count pairs with Bitwise XOR as EVEN number | Function to count number of even pairs ; find all pairs ; return number of even pair ; Driver Code ; calling function findEvenPair and pr number of even pair
def findEvenPair ( A , N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( A [ i ] % 2 != 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT totalPairs = ( N * ( N - 1 ) / 2 ) NEW_LINE oddEvenPairs = count * ( N - count ) NEW_LINE return ( int ) ( totalPairs - oddEvenPairs ) NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT a = [ 5 , 4 , 7 , 2 , 1 ] NEW_LINE n = len ( a ) NEW_LINE print ( findEvenPair ( a , n ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT
Count pairs with Bitwise | Function to count number of pairs EVEN bitwise AND ; variable for counting even pairs ; find all pairs ; find AND operation to check evenpair ; return number of even pair ; Driver Code
def findevenPair ( A , N ) : NEW_LINE INDENT evenPair = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( ( A [ i ] & A [ j ] ) % 2 == 0 ) : NEW_LINE INDENT evenPair += 1 NEW_LINE DEDENT DEDENT DEDENT return evenPair NEW_LINE DEDENT a = [ 5 , 1 , 3 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( findevenPair ( a , n ) ) NEW_LINE
Count pairs with Bitwise | Function to count number of pairs with EVEN bitwise AND ; count odd numbers ; count odd pairs ; return number of even pair ; Driver Code
def findevenPair ( A , N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( A [ i ] % 2 != 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT oddCount = count * ( count - 1 ) / 2 NEW_LINE return ( int ) ( ( N * ( N - 1 ) / 2 ) - oddCount ) NEW_LINE DEDENT a = [ 5 , 1 , 3 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( findevenPair ( a , n ) ) NEW_LINE
Find a value whose XOR with given number is maximum | Function To Calculate Answer ; Find number of bits in the given integer ; XOR the given integer with poe ( 2 , number_of_bits - 1 and print the result ; Driver Code
def calculate ( X ) : NEW_LINE INDENT number_of_bits = 8 NEW_LINE return ( ( 1 << number_of_bits ) - 1 ) ^ X NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 4 NEW_LINE print ( " Required ▁ Number ▁ is : " , calculate ( X ) ) NEW_LINE DEDENT
XOR of all elements of array with set bits equal to K | Function to find Xor of desired elements ; Initialize vector ; push required elements ; Initialize result with first element of vector ; Driver code
def xorGivenSetBits ( arr , n , k ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( bin ( arr [ i ] ) . count ( '1' ) == k ) : NEW_LINE INDENT v . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT result = v [ 0 ] NEW_LINE for i in range ( 1 , len ( v ) , 1 ) : NEW_LINE INDENT result = result ^ v [ i ] NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 13 , 1 , 19 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( xorGivenSetBits ( arr , n , k ) ) NEW_LINE DEDENT
Replace every element of the array with BitWise XOR of all other | Function to replace the elements ; Calculate the xor of all the elements ; Replace every element by the xor of all other elements ; Driver code ; Print the modified array .
def ReplaceElements ( arr , n ) : NEW_LINE INDENT X = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT X ^= arr [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = X ^ arr [ i ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 3 , 5 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE ReplaceElements ( arr , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT
Assign other value to a variable from two possible values | Function to alternate the values ; Driver code
def alternate ( a , b , x ) : NEW_LINE INDENT x = a ^ b ^ x NEW_LINE print ( " After ▁ exchange " ) NEW_LINE print ( " x ▁ is " , x ) NEW_LINE DEDENT a = - 10 NEW_LINE b = 15 NEW_LINE x = a NEW_LINE print ( " x ▁ is " , x ) NEW_LINE alternate ( a , b , x ) NEW_LINE
Number of leading zeros in binary representation of a given number | Function to count the no . of leading zeros ; Keep shifting x by one until leftmost bit does not become 1. ; Driver Code
def countZeros ( x ) : NEW_LINE INDENT total_bits = 32 NEW_LINE res = 0 NEW_LINE while ( ( x & ( 1 << ( total_bits - 1 ) ) ) == 0 ) : NEW_LINE INDENT x = ( x << 1 ) NEW_LINE res += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT x = 101 NEW_LINE print ( countZeros ( x ) ) NEW_LINE
Number of leading zeros in binary representation of a given number | Function to count the no . of leading zeros ; Main function
def countZeros ( x ) : NEW_LINE INDENT n = 32 ; NEW_LINE y = x >> 16 ; NEW_LINE if ( y != 0 ) : NEW_LINE INDENT n = n - 16 ; NEW_LINE x = y ; NEW_LINE DEDENT y = x >> 8 ; NEW_LINE if ( y != 0 ) : NEW_LINE INDENT n = n - 8 ; NEW_LINE x = y ; NEW_LINE DEDENT y = x >> 4 ; NEW_LINE if ( y != 0 ) : NEW_LINE INDENT n = n - 4 ; NEW_LINE x = y ; NEW_LINE DEDENT y = x >> 2 ; NEW_LINE if ( y != 0 ) : NEW_LINE INDENT n = n - 2 ; NEW_LINE x = y ; NEW_LINE DEDENT y = x >> 1 ; NEW_LINE if ( y != 0 ) : NEW_LINE INDENT return n - 2 ; NEW_LINE DEDENT return n - x ; NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT x = 101 ; NEW_LINE print ( countZeros ( x ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT
Comparing leading zeros in binary representations of two numbers | Function to compare the no . of leading zeros ; if both have same no . of leading zeros ; if y has more leading zeros ; Driver Code
def LeadingZeros ( x , y ) : NEW_LINE INDENT if ( ( x ^ y ) <= ( x & y ) ) : NEW_LINE INDENT print ( " Equal " ) NEW_LINE DEDENT elif ( ( x & ( ~ y ) ) > y ) : NEW_LINE INDENT print ( y ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( x ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 10 NEW_LINE y = 16 NEW_LINE LeadingZeros ( x , y ) NEW_LINE DEDENT
Printing all subsets of { 1 , 2 , 3 , ... n } without using array or loop | This recursive function calls subset function to print the subsets one by one . numBits -- > number of bits needed to represent the number ( simply input value n ) . num -- > Initially equal to 2 ^ n - 1 and decreases by 1 every recursion until 0. ; Print the subset corresponding to binary representation of num . ; Call the function recursively to print the next subset . ; This function recursively prints the subset corresponding to the binary representation of num . nthBit -- > nth bit from right side starting from n and decreases until 0. ; Print number in given subset only if the bit corresponding to it is set in num . ; Check for the next bit ; Driver Code
def printSubsets ( numOfBits , num ) : NEW_LINE INDENT if num >= 0 : NEW_LINE INDENT print ( " { " , end = " ▁ " ) NEW_LINE subset ( numOfBits - 1 , num , numOfBits ) NEW_LINE print ( " } " ) NEW_LINE printSubsets ( numOfBits , num - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return NEW_LINE DEDENT DEDENT def subset ( nthBit , num , numOfBits ) : NEW_LINE INDENT if nthBit >= 0 : NEW_LINE INDENT if num & ( 1 << nthBit ) != 0 : NEW_LINE INDENT print ( numOfBits - nthBit , end = " ▁ " ) NEW_LINE DEDENT subset ( nthBit - 1 , num , numOfBits ) NEW_LINE DEDENT else : NEW_LINE INDENT return NEW_LINE DEDENT DEDENT n = 4 NEW_LINE printSubsets ( n , 2 ** n - 1 ) NEW_LINE
Number of mismatching bits in the binary representation of two integers | compute number of different bits ; since , the numbers are less than 2 ^ 31 run the loop from '0' to '31' only ; right shift both the numbers by ' i ' and check if the bit at the 0 th position is different ; Driver code ; find number of different bits
def solve ( A , B ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , 32 ) : NEW_LINE INDENT if ( ( ( A >> i ) & 1 ) != ( ( B >> i ) & 1 ) ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT print ( " Number ▁ of ▁ different ▁ bits ▁ : " , count ) NEW_LINE DEDENT A = 12 NEW_LINE B = 15 NEW_LINE solve ( A , B ) NEW_LINE
Set the rightmost off bit | Python3 program to set the rightmost unset bit ; If all bits are set ; Set rightmost 0 bit ; Driver code
def setRightmostUnsetBit ( n ) : NEW_LINE INDENT if n & ( n + 1 ) == 0 : NEW_LINE INDENT return n NEW_LINE DEDENT return n | ( n + 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 21 NEW_LINE print ( setRightmostUnsetBit ( n ) ) NEW_LINE DEDENT
Print the number of set bits in each node of a Binary Tree | Binary Tree node ; Utility function that allocates a new Node ; Function to print the number of set bits in each node of the binary tree ; Print the number of set bits of current node using count ( ) ; Traverse Left Subtree ; Traverse Right Subtree ; Driver Code
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = None NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT node = Node ( ) NEW_LINE node . data = data NEW_LINE node . left = None NEW_LINE node . right = None NEW_LINE return node NEW_LINE DEDENT def printSetBit ( root : Node ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT print ( " Set ▁ bits ▁ in ▁ Node ▁ % d ▁ = ▁ % d " % ( root . data , bin ( root . data ) . count ( '1' ) ) ) NEW_LINE printSetBit ( root . left ) NEW_LINE printSetBit ( root . right ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = newNode ( 16 ) NEW_LINE root . left = newNode ( 13 ) NEW_LINE root . left . left = newNode ( 14 ) NEW_LINE root . left . right = newNode ( 12 ) NEW_LINE root . right = newNode ( 11 ) NEW_LINE root . right . left = newNode ( 10 ) NEW_LINE root . right . right = newNode ( 16 ) NEW_LINE printSetBit ( root ) NEW_LINE DEDENT
Find bitwise AND ( & ) of all possible sub | function to return AND of sub - arrays ; Driver Code ; size of the array ; print and of all subarrays
def AND ( a , n ) : NEW_LINE INDENT ans = a [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans &= a [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( AND ( a , n ) ) NEW_LINE DEDENT
2 's complement for a givin string using XOR | Python program to find 2 's complement using XOR. ; A flag used to find if a 1 bit is seen or not . ; xor operator is used to flip the ; bits after converting in to ASCII values ; if there is no 1 in the string so just add 1 in starting of string and return ; Driver code
def TwoscomplementbyXOR ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE check_bit = 0 NEW_LINE i = n - 1 NEW_LINE s = list ( str ) NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( s [ i ] == '0' and check_bit == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT if ( check_bit == 1 ) : NEW_LINE INDENT s [ i ] = chr ( ( ord ( s [ i ] ) - 48 ) ^ 1 + 48 ) NEW_LINE DEDENT check_bit = 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT str = " " . join ( s ) NEW_LINE if ( check_bit == 0 ) : NEW_LINE INDENT return "1" + str NEW_LINE DEDENT else : NEW_LINE INDENT return str NEW_LINE DEDENT DEDENT str = "101" NEW_LINE print ( TwoscomplementbyXOR ( str ) ) NEW_LINE
Check whether bits are in alternate pattern in the given range | Set | function to check whether rightmost kth bit is set or not in 'n ; function to set the rightmost kth bit in 'n ; kth bit of n is being set by this operation ; function to check if all the bits are set or not in the binary representation of 'n ; if true , then all bits are set ; else all bits are not set ; function to check if a number has bits in alternate pattern ; to check if all bits are set in 'num ; function to check whether bits are in alternate pattern in the given range ; preparing a number ' num ' and ' left _ shift ' which can be further used for the check of alternate pattern in the given range ; unset all the bits which are left to the rth bit of ( r + 1 ) th bit ; right shift ' num ' by ( l - 1 ) bits ; Driver Code
' NEW_LINE def isKthBitSet ( n , k ) : NEW_LINE INDENT if ( ( n >> ( k - 1 ) ) & 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT ' NEW_LINE def setKthBit ( n , k ) : NEW_LINE INDENT return ( ( 1 << ( k - 1 ) ) n ) NEW_LINE DEDENT ' NEW_LINE def allBitsAreSet ( n ) : NEW_LINE INDENT if ( ( ( n + 1 ) & n ) == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def bitsAreInAltOrder ( n ) : NEW_LINE INDENT num = n ^ ( n >> 1 ) NEW_LINE DEDENT ' NEW_LINE INDENT return allBitsAreSet ( num ) NEW_LINE DEDENT def bitsAreInAltPatrnInGivenRange ( n , l , r ) : NEW_LINE INDENT if ( isKthBitSet ( n , r ) ) : NEW_LINE INDENT num = n NEW_LINE left_shift = r NEW_LINE DEDENT else : NEW_LINE INDENT num = setKthBit ( n , ( r + 1 ) ) NEW_LINE left_shift = r + 1 NEW_LINE DEDENT num = num & ( ( 1 << left_shift ) - 1 ) NEW_LINE num = num >> ( l - 1 ) NEW_LINE return bitsAreInAltOrder ( num ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 18 NEW_LINE l = 1 NEW_LINE r = 3 NEW_LINE if ( bitsAreInAltPatrnInGivenRange ( n , l , r ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Increment a number without using ++ or + | function that increment the value . ; Invert bits and apply negative sign ; Driver code
def increment ( i ) : NEW_LINE INDENT i = - ( ~ i ) ; NEW_LINE return i ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 ; NEW_LINE print ( increment ( n ) ) ; NEW_LINE DEDENT
First element greater than or equal to X in prefix sum of N numbers using Binary Lifting | Python 3 program to find lower_bound of x in prefix sums array using binary lifting . ; function to make prefix sums array ; function to find lower_bound of x in prefix sums array using binary lifting . ; initialize position ; find log to the base 2 value of n . ; if x less than first number . ; starting from most significant bit . ; if value at this position less than x then updateposition Here ( 1 << i ) is similar to 2 ^ i . ; + 1 because ' pos ' will have position of largest value less than 'x ; Driver code ; given array ; value to find ; size of array ; to store prefix sum ; call for prefix sum ; function call
import math NEW_LINE def MakePreSum ( arr , presum , n ) : NEW_LINE INDENT presum [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT presum [ i ] = presum [ i - 1 ] + arr [ i ] NEW_LINE DEDENT DEDENT def BinaryLifting ( presum , n , x ) : NEW_LINE INDENT pos = 0 NEW_LINE LOGN = int ( math . log2 ( n ) ) NEW_LINE if ( x <= presum [ 0 ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for i in range ( LOGN , - 1 , - 1 ) : NEW_LINE INDENT if ( pos + ( 1 << i ) < n and presum [ pos + ( 1 << i ) ] < x ) : NEW_LINE INDENT pos += ( 1 << i ) NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT return pos + 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 5 , 7 , 1 , 6 , 9 , 12 , 4 , 6 ] NEW_LINE x = 8 NEW_LINE n = len ( arr ) NEW_LINE presum = [ 0 ] * n NEW_LINE MakePreSum ( arr , presum , n ) NEW_LINE print ( BinaryLifting ( presum , n , x ) ) NEW_LINE DEDENT
Maximum sum by adding numbers with same number of set bits | count the number of bits for each element of array ; Count the number of set bits ; Function to return the the maximum sum ; Calculate the ; Assuming the number to be a maximum of 32 bits ; Add the number to the number of set bits ; Find the maximum sum ; Driver code
def bit_count ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE n = n & ( n - 1 ) ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT def maxsum ( arr , n ) : NEW_LINE INDENT bits = [ 0 ] * n ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT bits [ i ] = bit_count ( arr [ i ] ) ; NEW_LINE DEDENT sum = [ 0 ] * 32 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum [ bits [ i ] ] += arr [ i ] ; NEW_LINE DEDENT maximum = 0 ; NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT maximum = max ( sum [ i ] , maximum ) ; NEW_LINE DEDENT return maximum ; NEW_LINE DEDENT arr = [ 2 , 3 , 8 , 5 , 6 , 7 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maxsum ( arr , n ) ) ; NEW_LINE
Sum of XOR of sum of all pairs in an array | Python3 program to find XOR of pair sums . ; Driver program to test the above function
def xor_pair_sum ( ar , n ) : NEW_LINE INDENT total = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT total = total ^ ar [ i ] NEW_LINE DEDENT return 2 * total NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT data = [ 1 , 2 , 3 ] NEW_LINE print ( xor_pair_sum ( data , len ( data ) ) ) NEW_LINE DEDENT
Count pairs with Bitwise OR as Even number | Python 3 program to count pairs with even OR ; Count total even numbers in array . ; return count of even pair ; Driver Code
def findEvenPair ( A , N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( not ( A [ i ] & 1 ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count * ( count - 1 ) // 2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 5 , 6 , 2 , 8 ] NEW_LINE N = len ( A ) NEW_LINE print ( findEvenPair ( A , N ) ) NEW_LINE DEDENT
Check whether all the bits are unset in the given range | function to check whether all the bits are unset in the given range or not ; calculating a number ' num ' having ' r ' number of bits and bits in the range l to r are the only set bits ; new number which could only have one or more set bits in the range l to r and nowhere else ; if true , then all bits are unset in the given range ; else all bits are not unset in the given range ; Driver Code
def allBitsSetInTheGivenRange ( n , l , r ) : NEW_LINE INDENT num = ( ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ) NEW_LINE new_num = n & num NEW_LINE if ( new_num == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return false NEW_LINE DEDENT n = 17 NEW_LINE l = 2 NEW_LINE r = 4 NEW_LINE if ( allBitsSetInTheGivenRange ( n , l , r ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Check if a number has same number of set and unset bits | Function to check if a number has same setbits and unset bits ; iterate for all bits of a number ; if set ; if unset ; right shift number by 1 ; is number of set bits are equal to unset bits ; Driver Code ; function to check
def checkSame ( n ) : NEW_LINE INDENT set , unset = 0 , 0 NEW_LINE while ( n ) : NEW_LINE INDENT if ( n and 1 ) : NEW_LINE INDENT set + 1 NEW_LINE DEDENT else : NEW_LINE INDENT unset += 1 NEW_LINE DEDENT n = n >> 1 NEW_LINE DEDENT if ( set == unset ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12 NEW_LINE if ( checkSame ( n ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT
Check if concatenation of two strings is balanced or not | Check if given string is balanced bracket sequence or not . ; If current bracket is an opening bracket push it to stack . ; If current bracket is a closing bracket then pop from stack if it is not empty . If stack is empty then sequence is not balanced . ; If stack is not empty , then sequence is not balanced . ; Function to check if string obtained by concatenating two bracket sequences is balanced or not . ; Check if s1 + s2 is balanced or not . ; Check if s2 + s1 is balanced or not . ; Driver Code
def isBalanced ( s ) : NEW_LINE INDENT st = list ( ) NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if s [ i ] == ' ( ' : NEW_LINE INDENT st . append ( s [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT if len ( st ) == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT st . pop ( ) NEW_LINE DEDENT DEDENT DEDENT if len ( st ) > 0 : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def isBalancedSeq ( s1 , s2 ) : NEW_LINE INDENT if ( isBalanced ( s1 + s2 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return isBalanced ( s2 + s1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : s1 = " ) ( ) ( ( ) ) ) ) " NEW_LINE INDENT s2 = " ( ( ) ( ( ) ( " NEW_LINE if isBalancedSeq ( s1 , s2 ) : NEW_LINE INDENT print ( " Balanced " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Balanced " ) NEW_LINE DEDENT DEDENT
Find iΓ’ €ℒ th index character in a binary string obtained after n iterations | Set 2 | Function to find the i - th character ; distance between two consecutive elements after N iterations ; binary representation of M ; kth digit will be derived from root for sure ; Check whether there is need to flip root or not ; Driver Code
def KthCharacter ( m , n , k ) : NEW_LINE INDENT distance = pow ( 2 , n ) NEW_LINE Block_number = int ( k / distance ) NEW_LINE remaining = k % distance NEW_LINE s = [ 0 ] * 32 NEW_LINE x = 0 NEW_LINE while ( m > 0 ) : NEW_LINE INDENT s [ x ] = m % 2 NEW_LINE m = int ( m / 2 ) NEW_LINE x += 1 NEW_LINE DEDENT root = s [ x - 1 - Block_number ] NEW_LINE if ( remaining == 0 ) : NEW_LINE INDENT print ( root ) NEW_LINE return NEW_LINE DEDENT flip = True NEW_LINE while ( remaining > 1 ) : NEW_LINE INDENT if ( remaining & 1 ) : NEW_LINE INDENT flip = not ( flip ) NEW_LINE DEDENT remaining = remaining >> 1 NEW_LINE DEDENT if ( flip ) : NEW_LINE INDENT print ( not ( root ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( root ) NEW_LINE DEDENT DEDENT m = 5 NEW_LINE k = 5 NEW_LINE n = 3 NEW_LINE KthCharacter ( m , n , k ) NEW_LINE
Check whether the number has only first and last bits set | Set 2 | function to check whether the number has only first and last bits set ; Driver Code
def onlyFirstAndLastAreSet ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n == 2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return ( ( ( n - 1 ) & ( n - 2 ) ) == 0 ) NEW_LINE DEDENT n = 9 NEW_LINE if ( onlyFirstAndLastAreSet ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Number with set bits only between L | Python 3 program to print the integer with all the bits set in range L - R Naive Approach ; Function to return the integer with all the bits set in range L - R ; iterate from L to R and add all powers of 2 ; Driver Code
from math import pow NEW_LINE def getInteger ( L , R ) : NEW_LINE INDENT number = 0 NEW_LINE for i in range ( L , R + 1 , 1 ) : NEW_LINE INDENT number += pow ( 2 , i ) NEW_LINE DEDENT return number NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 2 NEW_LINE R = 5 NEW_LINE print ( int ( getInteger ( L , R ) ) ) NEW_LINE DEDENT
Number with set bits only between L | Function to return the integer with all the bits set in range L - R ; Driver Code
def setbitsfromLtoR ( L , R ) : NEW_LINE INDENT return ( ( 1 << ( R + 1 ) ) - ( 1 << L ) ) NEW_LINE DEDENT L = 2 NEW_LINE R = 5 NEW_LINE print ( setbitsfromLtoR ( L , R ) ) NEW_LINE
XOR of Sum of every possible pair of an array | Function to find XOR of sum of all pairs ; Calculate xor of all the elements ; Return twice of xor value ; Driver code
def findXor ( arr , n ) : NEW_LINE INDENT xoR = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT xoR = xoR ^ arr [ i ] NEW_LINE DEDENT return xoR * 2 NEW_LINE DEDENT arr = [ 1 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findXor ( arr , n ) ) NEW_LINE
Largest set with bitwise OR equal to n | function to find the largest set with bitwise OR equal to n ; If the bitwise OR of n and i is equal to n , then include i in the set ; Driver Code
def setBitwiseORk ( n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( 0 , n + 1 , 1 ) : NEW_LINE INDENT if ( ( i n ) == n ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT DEDENT for i in range ( 0 , len ( v ) , 1 ) : NEW_LINE INDENT print ( v [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE setBitwiseORk ( n ) NEW_LINE DEDENT
Two odd occurring elements in an array where all other occur even times | Python 3 code to find two odd occurring elements in an array where all other elements appear even number of times . ; Find XOR of all numbers ; Find a set bit in the XOR ( We find rightmost set bit here ) ; Traverse through all numbers and divide them in two groups ( i ) Having set bit set at same position as the only set bit in set_bit ( ii ) Having 0 bit at same position as the only set bit in set_bit ; XOR of two different sets are our required numbers . ; Driver code
def printOdds ( arr , n ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT res = res ^ arr [ i ] NEW_LINE DEDENT set_bit = res & ( ~ ( res - 1 ) ) NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] & set_bit ) : NEW_LINE INDENT x = x ^ arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT y = y ^ arr [ i ] NEW_LINE DEDENT DEDENT print ( x , y , end = " " ) NEW_LINE DEDENT arr = [ 2 , 3 , 3 , 4 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE printOdds ( arr , n ) NEW_LINE
Maximum subset with bitwise OR equal to k | function to find the maximum subset with bitwise OR equal to k ; If the bitwise OR of k and element is equal to k , then include that element in the subset ; Store the bitwise OR of elements in v ; If ans is not equal to k , subset doesn 't exist ; Driver Code
def subsetBitwiseORk ( arr , n , k ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( ( arr [ i ] k ) == k ) : NEW_LINE INDENT v . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( 0 , len ( v ) ) : NEW_LINE INDENT ans |= v [ i ] NEW_LINE DEDENT if ( ans != k ) : NEW_LINE INDENT print ( " Subset does not exist " ) NEW_LINE return NEW_LINE DEDENT for i in range ( 0 , len ( v ) ) : NEW_LINE INDENT print ( " { } ▁ " . format ( v [ i ] ) , end = " " ) NEW_LINE DEDENT DEDENT k = 3 NEW_LINE arr = [ 1 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE subsetBitwiseORk ( arr , n , k ) NEW_LINE
Number whose XOR sum with given array is a given number k | This function returns the number to be inserted in the given array ; initialise the answer with k ; ans ^= A [ i ] XOR of all elements in the array ; Driver Code
def findEletobeInserted ( A , n , k ) : NEW_LINE INDENT ans = k NEW_LINE for i in range ( n ) : NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( A ) NEW_LINE k = 10 NEW_LINE print ( findEletobeInserted ( A , n , k ) , " has ▁ to ▁ be ▁ inserted ▁ in ▁ the ▁ given " , " array ▁ to ▁ make ▁ xor ▁ sum ▁ of " , k ) NEW_LINE DEDENT
Range query for count of set bits | 2 - D array that will stored the count of bits set in element of array ; Function store the set bit count in BitCount Array ; traverse over all bits ; mark elements with i 'th bit set ; Check whether the current bit is set or not if it 's set then mark it. ; store cumulative sum of bits ; Function to process queries ; Driver Code
BitCount = [ 0 ] * 10000 NEW_LINE def fillSetBitsmatrix ( arr : list , n : int ) : NEW_LINE INDENT global BitCount NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT temp = arr [ j ] >> i NEW_LINE if temp % 2 != 0 : NEW_LINE INDENT BitCount [ j ] += 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT BitCount [ i ] += BitCount [ i - 1 ] NEW_LINE DEDENT DEDENT def Query ( Q : list , q : int ) : NEW_LINE INDENT for i in range ( q ) : NEW_LINE INDENT print ( BitCount [ Q [ i ] [ 1 ] ] - BitCount [ Q [ i ] [ 0 ] - 1 ] ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT Arr = [ 1 , 5 , 6 , 10 , 9 , 4 , 67 ] NEW_LINE n = len ( Arr ) NEW_LINE fillSetBitsmatrix ( Arr , n ) NEW_LINE q = 2 NEW_LINE Q = [ ( 1 , 5 ) , ( 2 , 6 ) ] NEW_LINE Query ( Q , q ) NEW_LINE DEDENT
Generate n | Function to convert decimal to binary ; leftmost digits are filled with 0 ; Function to generate gray code ; generate gray code of corresponding binary number of integer i . ; printing gray code ; Driver code
def decimalToBinaryNumber ( x , n ) : NEW_LINE INDENT binaryNumber = [ 0 ] * x ; NEW_LINE i = 0 ; NEW_LINE while ( x > 0 ) : NEW_LINE INDENT binaryNumber [ i ] = x % 2 ; NEW_LINE x = x // 2 ; NEW_LINE i += 1 ; NEW_LINE DEDENT for j in range ( 0 , n - i ) : NEW_LINE INDENT print ( '0' , end = " " ) ; NEW_LINE DEDENT for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( binaryNumber [ j ] , end = " " ) ; NEW_LINE DEDENT DEDENT def generateGrayarr ( n ) : NEW_LINE INDENT N = 1 << n ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = i ^ ( i >> 1 ) ; NEW_LINE decimalToBinaryNumber ( x , n ) ; NEW_LINE print ( ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 ; NEW_LINE generateGrayarr ( n ) ; NEW_LINE DEDENT
Sum of bitwise AND of all possible subsets of given set | Python3 program to calculate sum of Bit - wise and sum of all subsets of an array ; assuming representation of each element is in 32 bit ; iterating array element ; Counting the set bit of array in ith position ; counting subset which produce sum when particular bit position is set . ; multiplying every position subset with 2 ^ i to count the sum . ; Driver code
BITS = 32 ; NEW_LINE def andSum ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , BITS ) : NEW_LINE INDENT countSetBits = 0 NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ j ] & ( 1 << i ) ) : NEW_LINE INDENT countSetBits = ( countSetBits + 1 ) NEW_LINE DEDENT DEDENT subset = ( ( 1 << countSetBits ) - 1 ) NEW_LINE subset = ( subset * ( 1 << i ) ) NEW_LINE ans = ans + subset NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 2 , 3 ] NEW_LINE size = len ( arr ) NEW_LINE print ( andSum ( arr , size ) ) NEW_LINE
Maximize the number by rearranging bits | An efficient python3 program to find minimum number formed by bits of a given number . ; Returns maximum number formed by bits of a given number . ; _popcnt32 ( a ) gives number of 1 's present in binary representation of a. ; If all 32 bits are set . ; Find a number witn n least significant set bits . ; Now shift result by 32 - n ; Driver code
def _popcnt32 ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT n = n & ( n - 1 ) NEW_LINE count = count + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def maximize ( a ) : NEW_LINE INDENT n = _popcnt32 ( a ) NEW_LINE if ( n == 32 ) : NEW_LINE INDENT return a NEW_LINE DEDENT res = ( 1 << n ) - 1 NEW_LINE return ( res << ( 32 - n ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 3 NEW_LINE print ( maximize ( a ) ) NEW_LINE DEDENT
Minimum number using set bits of a given number | Returns minimum number formed by bits of a given number . ; _popcnt32 ( a ) gives number of 1 's present in binary representation of a. ; Driver Code
def minimize ( a ) : NEW_LINE INDENT n = bin ( a ) . count ( "1" ) NEW_LINE return ( pow ( 2 , n ) - 1 ) NEW_LINE DEDENT a = 11 NEW_LINE print ( minimize ( a ) ) NEW_LINE
Maximum steps to transform 0 to X with bitwise AND | Function to get no of set bits in binary representation of positive integer n ; Driver code
def countSetBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT count += n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT i = 3 NEW_LINE print ( countSetBits ( i ) ) NEW_LINE
Check a number is odd or even without modulus operator | Returns true if n is even , else odd ; Driver code
def isEven ( n ) : NEW_LINE INDENT isEven = True ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if isEven == True : NEW_LINE INDENT isEven = False ; NEW_LINE DEDENT else : NEW_LINE INDENT isEven = True ; NEW_LINE DEDENT DEDENT return isEven ; NEW_LINE DEDENT n = 101 ; NEW_LINE if isEven ( n ) == True : NEW_LINE INDENT print ( " Even " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Odd " ) ; NEW_LINE DEDENT
Check a number is odd or even without modulus operator | Returns true if n is even , else odd ; Return true if n / 2 does not result in a float value . ; Driver code
def isEven ( n ) : NEW_LINE INDENT return ( int ( n / 2 ) * 2 == n ) NEW_LINE DEDENT n = 101 NEW_LINE if ( isEven ( n ) != False ) : NEW_LINE INDENT print ( " Even " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Odd " ) NEW_LINE DEDENT
Bitwise recursive addition of two integers | Python program to do recursive addition of two integers ; If bitwise & is 0 , then there is not going to be any carry . Hence result of XOR is addition . ; Driver code
def add ( x , y ) : NEW_LINE INDENT keep = ( x & y ) << 1 ; NEW_LINE res = x ^ y ; NEW_LINE if ( keep == 0 ) : NEW_LINE INDENT return res ; NEW_LINE DEDENT return add ( keep , res ) ; NEW_LINE DEDENT print ( add ( 15 , 38 ) ) ; NEW_LINE
Count pairs in an array which have at least one digit common | Returns true if the pair is valid , otherwise false ; converting integers to strings ; Iterate over the strings and check if a character in first string is also present in second string , return true ; No common digit found ; Returns the number of valid pairs ; Iterate over all possible pairs ; Driver Code
def checkValidPair ( num1 , num2 ) : NEW_LINE INDENT s1 = str ( num1 ) NEW_LINE s2 = str ( num2 ) NEW_LINE for i in range ( len ( s1 ) ) : NEW_LINE INDENT for j in range ( len ( s2 ) ) : NEW_LINE INDENT if ( s1 [ i ] == s2 [ j ] ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT DEDENT return False ; NEW_LINE DEDENT def countPairs ( arr , n ) : NEW_LINE INDENT numberOfPairs = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( checkValidPair ( arr [ i ] , arr [ j ] ) ) : NEW_LINE INDENT numberOfPairs += 1 NEW_LINE DEDENT DEDENT DEDENT return numberOfPairs NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 12 , 24 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countPairs ( arr , n ) ) NEW_LINE DEDENT
Check if bitwise AND of any subset is power of two | Python3 Program to check if Bitwise AND of any subset is power of two ; Check for power of 2 or not ; Check if there exist a subset whose bitwise AND is power of 2. ; if there is only one element in the set . ; Finding a number with all bit sets . ; check all the positions at which the bit is set . ; include all those elements whose i - th bit is set ; check for the set contains elements make a power of 2 or not ; Driver Program
NUM_BITS = 32 NEW_LINE def isPowerOf2 ( num ) : NEW_LINE INDENT return ( num and ( num & ( num - 1 ) ) == 0 ) NEW_LINE DEDENT def checkSubsequence ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return isPowerOf2 ( arr [ 0 ] ) NEW_LINE DEDENT total = 0 NEW_LINE for i in range ( 0 , NUM_BITS ) : NEW_LINE INDENT total = total | ( 1 << i ) NEW_LINE DEDENT for i in range ( 0 , NUM_BITS ) : NEW_LINE INDENT ans = total NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ j ] & ( 1 << i ) ) : NEW_LINE INDENT ans = ans & arr [ j ] NEW_LINE DEDENT DEDENT if ( isPowerOf2 ( ans ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT arr = [ 12 , 13 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE if ( checkSubsequence ( arr , n ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT
Levelwise Alternating OR and XOR operations in Segment Tree | Python3 program to build levelwise OR / XOR alternating Segment tree ; A utility function to get the middle index from corner indexes . ; A recursive function that constructs Segment Tree for array [ ss . . se ] . ' si ' is index of current node in segment tree ' st ' , operation denotes which operation is carried out at that level to merge the left and right child . It 's either 0 or 1. ; If there is one element in array , store it in current node of segment tree and return ; If there are more than one elements , then recur for left and right subtrees and store the sum of values in this node ; Build the left and the right subtrees by using the fact that operation at level ( i + 1 ) = ! ( operation at level i ) ; merge the left and right subtrees by checking the operation to be carried . If operation = 1 , then do OR else XOR ; OR operation ; XOR operation ; Function to construct segment tree from given array . This function allocates memory for segment tree and calls constructSTUtil ( ) to fill the allocated memory ; Height of segment tree ; Maximum size of segment tree ; Allocate memory ; operation = 1 ( XOR ) if Height of tree is even else it is 0 ( OR ) for the root node ; Fill the allocated memory st ; Return the constructed segment tree ; Driver Code ; leaf nodes ; Build the segment tree ; Root node is at index 0 considering 0 - based indexing in segment Tree ; print value at rootIndex
import math NEW_LINE def getMid ( s , e ) : NEW_LINE INDENT return s + ( e - s ) // 2 NEW_LINE DEDENT def constructSTUtil ( arr , ss , se , st , si , operation ) : NEW_LINE INDENT if ( ss == se ) : NEW_LINE INDENT st [ si ] = arr [ ss ] NEW_LINE return NEW_LINE DEDENT mid = getMid ( ss , se ) NEW_LINE constructSTUtil ( arr , ss , mid , st , si * 2 + 1 , not operation ) NEW_LINE constructSTUtil ( arr , mid + 1 , se , st , si * 2 + 2 , not operation ) NEW_LINE if ( operation == 1 ) : NEW_LINE INDENT st [ si ] = ( st [ 2 * si + 1 ] st [ 2 * si + 2 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT st [ si ] = ( st [ 2 * si + 1 ] ^ st [ 2 * si + 2 ] ) NEW_LINE DEDENT DEDENT def constructST ( arr , n ) : NEW_LINE INDENT x = int ( math . ceil ( math . log2 ( n ) ) ) NEW_LINE max_size = 2 * int ( pow ( 2 , x ) ) - 1 NEW_LINE st = [ 0 ] * max_size NEW_LINE operationAtRoot = ( 0 if x % 2 == 0 else 1 ) NEW_LINE constructSTUtil ( arr , 0 , n - 1 , st , 0 , operationAtRoot ) NEW_LINE return st NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT leaves = [ 1 , 6 , 3 , 7 , 5 , 9 , 10 , 4 ] NEW_LINE n = len ( leaves ) NEW_LINE segmentTree = constructST ( leaves , n ) NEW_LINE rootIndex = 0 NEW_LINE print ( " Value ▁ at ▁ Root ▁ Node ▁ = ▁ " , segmentTree [ rootIndex ] ) NEW_LINE DEDENT
Leftover element after performing alternate Bitwise OR and Bitwise XOR operations on adjacent pairs | Python3 program to print the Leftover element after performing alternate Bitwise OR and Bitwise XOR operations to the pairs . ; count the step number ; if one element is there , it will be the answer ; at first step we do a bitwise OR ; keep on doing bitwise operations till the last element is left ; perform operations ; if step is the odd step ; else : even step ; answer when one element is left ; Driver Code ; 1 st query ; 2 nd query
N = 1000 NEW_LINE def lastElement ( a , n ) : NEW_LINE INDENT steps = 1 NEW_LINE v = [ [ ] for i in range ( n ) ] NEW_LINE if n == 1 : return a [ 0 ] NEW_LINE for i in range ( 0 , n , 2 ) : NEW_LINE INDENT v [ steps ] . append ( a [ i ] a [ i + 1 ] ) NEW_LINE DEDENT while len ( v [ steps ] ) > 1 : NEW_LINE INDENT steps += 1 NEW_LINE for i in range ( 0 , len ( v [ steps - 1 ] ) , 2 ) : NEW_LINE INDENT if steps & 1 : NEW_LINE INDENT v [ steps ] . append ( v [ steps - 1 ] [ i ] v [ steps - 1 ] [ i + 1 ] ) NEW_LINE v [ steps ] . append ( v [ steps - 1 ] [ i ] ^ v [ steps - 1 ] [ i + 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return v [ steps ] [ 0 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 4 , 5 , 6 ] NEW_LINE n = len ( a ) NEW_LINE index , value , a [ 0 ] = 0 , 2 , 2 NEW_LINE print ( lastElement ( a , n ) ) NEW_LINE index , value = 3 , 5 NEW_LINE value = 5 NEW_LINE a [ index ] = value NEW_LINE print ( lastElement ( a , n ) ) NEW_LINE DEDENT
Find the winner in nim | Function to find winner of NIM - game ; case when Alice is winner ; when Bob is winner ; Driver code
def findWinner ( A , n ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT res ^= A [ i ] NEW_LINE DEDENT if ( res == 0 or n % 2 == 0 ) : NEW_LINE INDENT return " Alice " NEW_LINE DEDENT else : NEW_LINE INDENT return " Bob " NEW_LINE DEDENT DEDENT A = [ 1 , 4 , 3 , 5 ] NEW_LINE n = len ( A ) NEW_LINE print ( " Winner ▁ = ▁ " , findWinner ( A , n ) ) NEW_LINE
Fibbinary Numbers ( No consecutive 1 s in binary ) | function to check whether a number is fibbinary or not ; if the number does not contain adjacent ones then ( n & ( n >> 1 ) ) operation results to 0 ; Not a fibbinary number ; Driver code
def isFibbinaryNum ( n ) : NEW_LINE INDENT if ( ( n & ( n >> 1 ) ) == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT n = 10 NEW_LINE if ( isFibbinaryNum ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Maximum XOR | Python3 program to obtain maximum XOR value sub - array ; Function to calculate maximum XOR value ; Return ( 2 ^ c - 1 ) ; Driver Code
import math NEW_LINE def maxXOR ( n , k ) : NEW_LINE INDENT c = int ( math . log ( n , 2 ) ) + 1 NEW_LINE return ( ( 1 << c ) - 1 ) NEW_LINE DEDENT n = 12 ; k = 3 NEW_LINE print ( maxXOR ( n , k ) ) NEW_LINE
Divide two integers without using multiplication , division and mod operator | Function to divide a by b and return floor value it ; Calculate sign of divisor i . e . , sign will be negative either one of them is negative only iff otherwise it will be positive ; remove sign of operands ; Initialize the quotient ; test down from the highest bit and accumulate the tentative value for valid bit ; if the sign value computed earlier is - 1 then negate the value of quotient ; Driver code
def divide ( dividend , divisor ) : NEW_LINE INDENT sign = ( - 1 if ( ( dividend < 0 ) ^ ( divisor < 0 ) ) else 1 ) ; NEW_LINE dividend = abs ( dividend ) ; NEW_LINE divisor = abs ( divisor ) ; NEW_LINE quotient = 0 ; NEW_LINE temp = 0 ; NEW_LINE for i in range ( 31 , - 1 , - 1 ) : NEW_LINE INDENT if ( temp + ( divisor << i ) <= dividend ) : NEW_LINE INDENT temp += divisor << i ; NEW_LINE quotient |= 1 << i ; NEW_LINE DEDENT DEDENT if sign == - 1 : NEW_LINE quotient = - quotient ; NEW_LINE return quotient ; NEW_LINE DEDENT a = 10 ; NEW_LINE b = 3 ; NEW_LINE print ( divide ( a , b ) ) ; NEW_LINE a = 43 ; NEW_LINE b = - 8 ; NEW_LINE print ( divide ( a , b ) ) ; NEW_LINE
XOR of two numbers after making length of their binary representations equal | Function to count the number of bits in binary representation of an integer ; initialize count ; count till n is non zero ; right shift by 1 i . e , divide by 2 ; Function to calculate the xor of two numbers by adding trailing zeros to the number having less number of bits in its binary representation . ; stores the minimum and maximum ; left shift if the number of bits are less in binary representation ; Driver Code
def count ( n ) : NEW_LINE INDENT c = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT c += 1 NEW_LINE n = n >> 1 NEW_LINE DEDENT return c NEW_LINE DEDENT def XOR ( a , b ) : NEW_LINE INDENT c = min ( a , b ) NEW_LINE d = max ( a , b ) NEW_LINE if ( count ( c ) < count ( d ) ) : NEW_LINE INDENT c = c << ( count ( d ) - count ( c ) ) NEW_LINE DEDENT return ( c ^ d ) NEW_LINE DEDENT a = 13 ; b = 5 NEW_LINE print ( XOR ( a , b ) ) NEW_LINE
Check if binary string multiple of 3 using DFA | Function to check if the binary String is divisible by 3. ; checking if the bit is nonzero ; checking if the nonzero bit is at even position ; Checking if the difference of non - zero oddbits and evenbits is divisible by 3. ; Driver Program
def CheckDivisibilty ( A ) : NEW_LINE INDENT oddbits = 0 ; NEW_LINE evenbits = 0 ; NEW_LINE for counter in range ( len ( A ) ) : NEW_LINE INDENT if ( A [ counter ] == '1' ) : NEW_LINE INDENT if ( counter % 2 == 0 ) : NEW_LINE INDENT evenbits += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT oddbits += 1 ; NEW_LINE DEDENT DEDENT DEDENT if ( abs ( oddbits - evenbits ) % 3 == 0 ) : NEW_LINE INDENT print ( " Yes " + " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " + " " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = "10101" ; NEW_LINE CheckDivisibilty ( A ) ; NEW_LINE DEDENT
Swap every two bits in bytes | Python program to swap every two bits in a byte . ; Extracting the high bit shift it to lowbit Extracting the low bit shift it to highbit ; driver Function
import math NEW_LINE def swapBitsInPair ( x ) : NEW_LINE INDENT return ( ( x & 0b10101010 ) >> 1 ) or ( ( x & 0b01010101 ) << 1 ) NEW_LINE DEDENT x = 4 ; NEW_LINE print ( swapBitsInPair ( x ) ) NEW_LINE
Alternate bits of two numbers to create a new number | set even bit of number n ; res for store 101010. . number ; generate number form of 101010. . ... till temp size ; if bit is even then generate number and or with res ; return set even bit number ; set odd bit of number m ; res for store 101010. . number ; generate number form of 101010. . . . till temp size ; if bit is even then generate number and or with res ; return set odd bit number ; set even bit of number n ; set odd bit of number m ; take OR with these number ; Driver code ; n = 1 0 1 0 ^ ^ m = 1 0 1 1 ^ ^ result = 1 0 1 1
def setevenbits ( n ) : NEW_LINE INDENT temp = n NEW_LINE count = 0 NEW_LINE res = 0 NEW_LINE while temp > 0 : NEW_LINE INDENT if count % 2 : NEW_LINE INDENT res |= ( 1 << count ) NEW_LINE DEDENT count += 1 NEW_LINE temp >>= 1 NEW_LINE DEDENT return ( n & res ) NEW_LINE DEDENT def setoddbits ( m ) : NEW_LINE INDENT temp = m NEW_LINE count = 0 NEW_LINE res = 0 NEW_LINE while temp > 0 : NEW_LINE INDENT if not count % 2 : NEW_LINE INDENT res |= ( 1 << count ) NEW_LINE DEDENT count += 1 NEW_LINE temp >>= 1 NEW_LINE DEDENT return ( m & res ) NEW_LINE DEDENT def getAlternateBits ( n , m ) : NEW_LINE INDENT tempn = setevenbits ( n ) NEW_LINE tempm = setoddbits ( m ) NEW_LINE return ( tempn tempm ) NEW_LINE DEDENT n = 10 NEW_LINE m = 11 NEW_LINE print ( getAlternateBits ( n , m ) ) NEW_LINE
For every set bit of a number toggle bits of other | function for the Nega_bit ; Driver program to test above
def toggleBits ( n1 , n2 ) : NEW_LINE INDENT return ( n1 ^ n2 ) NEW_LINE DEDENT n1 = 2 NEW_LINE n2 = 5 NEW_LINE print ( toggleBits ( n1 , n2 ) ) NEW_LINE
Toggle all even bits of a number | Returns a number which has all even bits of n toggled . ; Generate number form of 101010 . . till of same order as n ; if bit is even then generate number and or with res ; return toggled number ; Driver code
def evenbittogglenumber ( n ) : NEW_LINE INDENT res = 0 NEW_LINE count = 0 NEW_LINE temp = n NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT if ( count % 2 == 1 ) : NEW_LINE INDENT res = res | ( 1 << count ) NEW_LINE DEDENT count = count + 1 NEW_LINE temp >>= 1 NEW_LINE DEDENT return n ^ res NEW_LINE DEDENT n = 11 NEW_LINE print ( evenbittogglenumber ( n ) ) NEW_LINE
Toggle first and last bits of a number | Returns a number which has same bit count as n and has only first and last bits as set . ; set all the bit of the number ; Adding one to n now unsets all bits and moves MSB to one place . Now we shift the number by 1 and add 1. ; if number is 1 ; take XOR with first and last set bit number ; Driver code
def takeLandFsetbits ( n ) : NEW_LINE INDENT n = n | n >> 1 NEW_LINE n = n | n >> 2 NEW_LINE n = n | n >> 4 NEW_LINE n = n | n >> 8 NEW_LINE n = n | n >> 16 NEW_LINE return ( ( n + 1 ) >> 1 ) + 1 NEW_LINE DEDENT def toggleFandLbits ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return n ^ takeLandFsetbits ( n ) NEW_LINE DEDENT n = 10 NEW_LINE print ( toggleFandLbits ( n ) ) NEW_LINE
Odious number | Function to get no of set bits in binary representation of passed binary no . Please refer below for details of this function : https : www . geeksforgeeks . org / count - set - bits - in - an - integer ; Check if number is odious or not ; Driver Code
def countSetBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT n = n & ( n - 1 ) NEW_LINE count = count + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def checkOdious ( n ) : NEW_LINE INDENT return ( countSetBits ( n ) % 2 == 1 ) NEW_LINE DEDENT num = 32 NEW_LINE if ( checkOdious ( num ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Set the Left most unset bit | Set left most unset bit ; if number contain all 1 then return n ; Find position of leftmost unset bit ; if temp L . S . B is zero then unset bit pos is change ; return OR of number and unset bit pos ; Driver Function
def setleftmostunsetbit ( n ) : NEW_LINE INDENT if not ( n & ( n + 1 ) ) : NEW_LINE INDENT return n NEW_LINE DEDENT pos , temp , count = 0 , n , 0 NEW_LINE while temp : NEW_LINE INDENT if not ( temp & 1 ) : NEW_LINE INDENT pos = count NEW_LINE DEDENT count += 1 ; temp >>= 1 NEW_LINE DEDENT return ( n | ( 1 << ( pos ) ) ) NEW_LINE DEDENT n = 10 NEW_LINE print ( setleftmostunsetbit ( n ) ) NEW_LINE
Maximum XOR using K numbers from 1 to n | To return max xor sum of 1 to n using at most k numbers ; If k is 1 then maximum possible sum is n ; Finding number greater than or equal to n with most significant bit same as n . For example , if n is 4 , result is 7. If n is 5 or 6 , result is 7 ; Return res - 1 which denotes a number with all bits set to 1 ; Driver code
def maxXorSum ( n , k ) : NEW_LINE INDENT if k == 1 : NEW_LINE INDENT return n NEW_LINE DEDENT res = 1 NEW_LINE while res <= n : NEW_LINE INDENT res <<= 1 NEW_LINE DEDENT return res - 1 NEW_LINE DEDENT n = 4 NEW_LINE k = 3 NEW_LINE print ( maxXorSum ( n , k ) ) NEW_LINE
Increment a number by one by manipulating the bits | python 3 implementation to increment a number by one by manipulating the bits ; function to find the position of rightmost set bit ; function to toggle the last m bits ; calculating a number ' num ' having ' m ' bits and all are set ; toggle the last m bits and return the number ; function to increment a number by one by manipulating the bits ; get position of rightmost unset bit if all bits of ' n ' are set , then the bit left to the MSB is the rightmost unset bit ; kth bit of n is being set by this operation ; from the right toggle all the bits before the k - th bit ; required number ; Driver program
import math NEW_LINE def getPosOfRightmostSetBit ( n ) : NEW_LINE INDENT return math . log2 ( n & - n ) NEW_LINE DEDENT def toggleLastKBits ( n , k ) : NEW_LINE INDENT num = ( 1 << ( int ) ( k ) ) - 1 NEW_LINE return ( n ^ num ) NEW_LINE DEDENT def incrementByOne ( n ) : NEW_LINE INDENT k = getPosOfRightmostSetBit ( ~ n ) NEW_LINE n = ( ( 1 << ( int ) ( k ) ) n ) NEW_LINE if ( k != 0 ) : NEW_LINE INDENT n = toggleLastKBits ( n , k ) NEW_LINE DEDENT return n NEW_LINE DEDENT n = 15 NEW_LINE print ( incrementByOne ( n ) ) NEW_LINE
XNOR of two numbers | Python3 program to find XNOR of two numbers ; log ( n ) solution ; Make sure a is larger ; for last bit of a ; for last bit of b ; counter for count bit and set bit in xnor num ; for make new xnor number ; for set bits in new xnor number ; get last bit of a ; get last bit of b ; Check if current two bits are same ; counter for count bit ; Driver method
import math NEW_LINE def swap ( a , b ) : NEW_LINE INDENT temp = a NEW_LINE a = b NEW_LINE b = temp NEW_LINE DEDENT def xnor ( a , b ) : NEW_LINE INDENT if ( a < b ) : NEW_LINE INDENT swap ( a , b ) NEW_LINE DEDENT if ( a == 0 and b == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT a_rem = 0 NEW_LINE b_rem = 0 NEW_LINE count = 0 NEW_LINE xnornum = 0 NEW_LINE while ( a != 0 ) : NEW_LINE INDENT a_rem = a & 1 NEW_LINE b_rem = b & 1 NEW_LINE if ( a_rem == b_rem ) : NEW_LINE INDENT xnornum |= ( 1 << count ) NEW_LINE DEDENT count = count + 1 NEW_LINE a = a >> 1 NEW_LINE b = b >> 1 NEW_LINE DEDENT return xnornum ; NEW_LINE DEDENT a = 10 NEW_LINE b = 50 NEW_LINE print ( xnor ( a , b ) ) NEW_LINE
XNOR of two numbers | python program to find XNOR of two numbers ; Please refer below post for details of this function https : www . geeksforgeeks . org / toggle - bits - significant - bit / ; Make a copy of n as we are going to change it . ; Suppose n is 273 ( binary is 100010001 ) . It does following 100010001 | 010001000 = 110011001 ; This makes sure 4 bits ( From MSB and including MSB ) are set . It does following 110011001 | 001100110 = 111111111 ; Returns XNOR of num1 and num2 ; Make sure num1 is larger ; Driver code
import math NEW_LINE def togglebit ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT i = n NEW_LINE n = n | ( n >> 1 ) NEW_LINE n |= n >> 2 NEW_LINE n |= n >> 4 NEW_LINE n |= n >> 8 NEW_LINE n |= n >> 16 NEW_LINE return i ^ n NEW_LINE DEDENT def xnor ( num1 , num2 ) : NEW_LINE INDENT if ( num1 < num2 ) : NEW_LINE INDENT temp = num1 NEW_LINE num1 = num2 NEW_LINE num2 = temp NEW_LINE DEDENT num1 = togglebit ( num1 ) NEW_LINE return num1 ^ num2 NEW_LINE DEDENT a = 10 NEW_LINE b = 20 NEW_LINE print ( xnor ( a , b ) ) NEW_LINE
Maximum OR sum of sub | function to find maximum OR sum ; OR sum of all the elements in both arrays ; Driver Code
def MaximumSum ( a , b , n ) : NEW_LINE INDENT sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum1 |= a [ i ] NEW_LINE sum2 |= b [ i ] NEW_LINE DEDENT print ( sum1 + sum2 ) NEW_LINE DEDENT A = [ 1 , 2 , 4 , 3 , 2 ] NEW_LINE B = [ 2 , 3 , 3 , 12 , 1 ] NEW_LINE n = len ( A ) NEW_LINE MaximumSum ( A , B , n ) NEW_LINE
Position of rightmost bit with first carry in sum of two binary | Python3 implementation to find the position of rightmost bit where a carry is generated first ; function to find the position of rightmost set bit in 'n ; function to find the position of rightmost bit where a carry is generated first ; Driver program to test above
import math NEW_LINE ' NEW_LINE def posOfRightmostSetBit ( n ) : NEW_LINE INDENT return int ( math . log2 ( n & - n ) + 1 ) NEW_LINE DEDENT def posOfCarryBit ( a , b ) : NEW_LINE INDENT return posOfRightmostSetBit ( a & b ) NEW_LINE DEDENT a = 10 NEW_LINE b = 2 NEW_LINE print ( posOfCarryBit ( a , b ) ) NEW_LINE
Check whether the two numbers differ at one bit position only | function to check if x is power of 2 ; First x in the below expression is for the case when x is 0 ; function to check whether the two numbers differ at one bit position only ; Driver code to test above
def isPowerOfTwo ( x ) : NEW_LINE INDENT return x and ( not ( x & ( x - 1 ) ) ) NEW_LINE DEDENT def differAtOneBitPos ( a , b ) : NEW_LINE INDENT return isPowerOfTwo ( a ^ b ) NEW_LINE DEDENT a = 13 NEW_LINE b = 9 NEW_LINE if ( differAtOneBitPos ( a , b ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Multiplication with a power of 2 | Returns 2 raised to power n ; Driven program
def power2 ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT return power2 ( n / 2 ) * NEW_LINE INDENT power2 ( n / 2 ) ; NEW_LINE DEDENT DEDENT def multiply ( x , n ) : NEW_LINE INDENT return x * power2 ( n ) ; NEW_LINE DEDENT x = 70 NEW_LINE n = 2 NEW_LINE print ( multiply ( x , n ) ) NEW_LINE
Multiplication with a power of 2 | Efficient Python3 code to compute x * ( 2 ^ n ) ; Driven code to check above function
def multiply ( x , n ) : NEW_LINE INDENT return x << n NEW_LINE DEDENT x = 70 NEW_LINE n = 2 NEW_LINE print ( multiply ( x , n ) ) NEW_LINE
Check if n is divisible by power of 2 without using arithmetic operators | function to check whether n is divisible by pow ( 2 , m ) ; if expression results to 0 , then n is divisible by pow ( 2 , m ) ; n is not divisible ; Driver program to test above
def isDivBy2PowerM ( n , m ) : NEW_LINE INDENT if ( n & ( ( 1 << m ) - 1 ) ) == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT n = 8 NEW_LINE m = 2 NEW_LINE if isDivBy2PowerM ( n , m ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Game of Nim with removal of one stone allowed | Return true if player A wins , return false if player B wins . ; Checking the last bit of N . ; Driven Program
def findWinner ( N ) : NEW_LINE INDENT return N & 1 NEW_LINE DEDENT N = 15 NEW_LINE print ( " Player ▁ A " if findWinner ( N ) else " Player ▁ B " ) NEW_LINE
Toggle all odd bits of a number | Returns a number which has all odd bits of n toggled . ; Generate number form of 101010. . . . . till of same order as n ; If bit is odd , then generate number and or with res ; Return toggled number ; Driver code
def evenbittogglenumber ( n ) : NEW_LINE INDENT res = 0 ; count = 0 ; temp = n NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT if ( count % 2 == 0 ) : NEW_LINE INDENT res = res | ( 1 << count ) NEW_LINE DEDENT count = count + 1 NEW_LINE temp >>= 1 NEW_LINE DEDENT return n ^ res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 11 NEW_LINE print ( evenbittogglenumber ( n ) ) NEW_LINE DEDENT
Quotient and remainder dividing by 2 ^ k ( a power of 2 ) | Python 3 to find remainder and quotient ; function to print remainder and quotient ; print Remainder by n AND ( m - 1 ) ; print quotient by right shifting n by ( log2 ( m ) ) times ; driver program
import math NEW_LINE def divide ( n , m ) : NEW_LINE INDENT print ( " Remainder ▁ = ▁ " , ( ( n ) & ( m - 1 ) ) ) NEW_LINE print ( " Quotient ▁ = ▁ " , ( n >> ( int ) ( math . log2 ( m ) ) ) ) NEW_LINE DEDENT n = 43 NEW_LINE m = 8 NEW_LINE divide ( n , m ) NEW_LINE
Maximum AND value of a pair in an array | Function for finding maximum and value pair ; Driver function
def maxAND ( arr , n ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT res = max ( res , arr [ i ] & arr [ j ] ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 4 , 8 , 6 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum ▁ AND ▁ Value ▁ = ▁ " , maxAND ( arr , n ) ) NEW_LINE
Check if a number is positive , negative or zero using bit operators | function to return 1 if it is zero returns 0 if it is negative returns 2 if it is positive ; string array to store all kinds of number ; function call to check the sign of number ; driver program to test the above function
def index ( i ) : NEW_LINE INDENT return 1 + ( i >> 31 ) - ( - i >> 31 ) NEW_LINE DEDENT def check ( n ) : NEW_LINE INDENT s = " negative " , " zero " , " positive " NEW_LINE val = index ( n ) NEW_LINE print ( n , " is " , s [ val ] ) NEW_LINE DEDENT check ( 30 ) NEW_LINE check ( - 20 ) NEW_LINE check ( 0 ) NEW_LINE
Find two numbers from their sum and XOR | Function that takes in the sum and XOR of two numbers and generates the two numbers such that the value of X is minimized ; Traverse through all bits ; Let us leave bits as 0. ; else : ( Xi == 1 and Ai == 1 ) ; Driver function
def compute ( S , X ) : NEW_LINE INDENT A = ( S - X ) // 2 NEW_LINE a = 0 NEW_LINE b = 0 NEW_LINE for i in range ( 64 ) : NEW_LINE INDENT Xi = ( X & ( 1 << i ) ) NEW_LINE Ai = ( A & ( 1 << i ) ) NEW_LINE if ( Xi == 0 and Ai == 0 ) : NEW_LINE INDENT pass NEW_LINE DEDENT elif ( Xi == 0 and Ai > 0 ) : NEW_LINE INDENT a = ( ( 1 << i ) a ) NEW_LINE b = ( ( 1 << i ) b ) NEW_LINE DEDENT elif ( Xi > 0 and Ai == 0 ) : NEW_LINE INDENT a = ( ( 1 << i ) a ) NEW_LINE print ( " Not ▁ Possible " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " a ▁ = ▁ " , a ) NEW_LINE print ( " b ▁ = " , b ) NEW_LINE DEDENT S = 17 NEW_LINE X = 13 NEW_LINE compute ( S , X ) NEW_LINE
Divisibility by 64 with removal of bits allowed | function to check if it is possible to make it a multiple of 64. ; counter to count 0 's ; loop which traverses right to left and calculates the number of zeros before 1. ; Driver code
def checking ( s ) : NEW_LINE INDENT c = 0 NEW_LINE n = len ( s ) NEW_LINE i = n - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( c >= 6 and s [ i ] == '1' ) : NEW_LINE INDENT return True NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "100010001" NEW_LINE if ( checking ( s ) ) : NEW_LINE INDENT print ( " Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ possible " ) NEW_LINE DEDENT DEDENT
Modify a bit at a given position | Returns modified n . ; Driver code
def modifyBit ( n , p , b ) : NEW_LINE INDENT mask = 1 << p NEW_LINE return ( n & ~ mask ) | ( ( b << p ) & mask ) NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT print ( modifyBit ( 6 , 2 , 0 ) ) NEW_LINE print ( modifyBit ( 6 , 5 , 1 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT
Count set bits in a range | Function to get no of set bits in the binary representation of 'n ; function to count set bits in the given range ; calculating a number ' num ' having ' r ' number of bits and bits in the range l to r are the only set bits ; returns number of set bits in the range ' l ' to ' r ' in 'n ; Driver program to test above
' NEW_LINE def countSetBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT n &= ( n - 1 ) NEW_LINE count = count + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def countSetBitsInGivenRange ( n , l , r ) : NEW_LINE INDENT num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) NEW_LINE DEDENT ' NEW_LINE INDENT return countSetBits ( n & num ) NEW_LINE DEDENT n = 42 NEW_LINE l = 2 NEW_LINE r = 5 NEW_LINE ans = countSetBitsInGivenRange ( n , l , r ) NEW_LINE print ( ans ) NEW_LINE
Check if one of the numbers is one 's complement of the other | function to check if all the bits are set or not in the binary representation of 'n ; all bits are not set ; if True , then all bits are set ; else all bits are not set ; function to check if one of the two numbers is one 's complement of the other ; Driver program
' NEW_LINE def areAllBitsSet ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if ( ( ( n + 1 ) & n ) == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT def isOnesComplementOfOther ( a , b ) : NEW_LINE INDENT return areAllBitsSet ( a ^ b ) NEW_LINE DEDENT a = 1 NEW_LINE b = 14 NEW_LINE if ( isOnesComplementOfOther ( a , b ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT