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 INDEN... |
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 ... | 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 IN... |
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 functio... | 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_LIN... |
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 ) ^ ( ... | 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 DEDE... |
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 pas... | 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_LI... |
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 p... |
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 [ ... |
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__ ==... |
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 ... | 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 ... |
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 decim... | 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... |
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_L... |
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 ... |
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 ; D... | 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 INDEN... |
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 t... | 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 ... |
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 = [ ... |
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 INDEN... |
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 ) NE... |
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 ... |
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 ] N... |
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 = ... |
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 ( ... |
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... |
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 N... |
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... | 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 ( ... |
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... | 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 (... |
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 C... | 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 ret... |
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 IN... |
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 tr... | ' 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 ( (... |
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 ; fi... | 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 ... |
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 ; Dri... | 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 [... |
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... |
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 a... | 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 ( allBitsSetInTheGiv... |
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 ... |
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 s... | 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 . p... |
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 ; Driv... | 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 [... |
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... |
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 (... |
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__ == ' _ _ m... |
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... | 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 ]... |
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 != ... |
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 β in... |
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 b... | 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 f... |
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... |
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... | 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 << c... |
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 le... | 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... |
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_L... |
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 pai... | 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 DED... |
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 pos... | 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 I... |
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 t... | 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 (... |
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... | 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... |
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... |
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 ... | 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... |
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 n... | 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 ) - co... |
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 D... |
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... | 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 tem... |
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_LI... |
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... | 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 ... |
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 ) ) ... |
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 ) )... |
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 denote... | 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 retur... | 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 ( ~ ... |
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 t... | 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_LI... |
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 | 010... | 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 (... |
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 Maxim... |
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... | 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... |
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 = ... |
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 DEDE... |
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 _... |
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 β AN... |
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 = ... |
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 DEDE... |
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_LI... |
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 ; Dri... | ' 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 '... |
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 ; Drive... | ' 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.