text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Range Sum Queries and Update with Square Root | CPP 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 ; if it crosses the right index of query or end of set , then break ; update the value of arr [ i ] to its 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; int BIT [ MAX + 1 ] ; struct queries { int type , l , r ; } ; void update ( int x , int val , int n ) { for ( x ; x <= n ; x += x & - x ) { BIT [ x ] += val ; } } int sum ( int x ) { int s = 0 ; for ( x ; x > 0 ; x -= x & - x ) { s += BIT [ x ] ; } return s ; } void answerQueries ( int arr [ ] , queries que [ ] , int n , int q ) { set < int > s ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] > 1 ) s . insert ( i ) ; update ( i , arr [ i ] , n ) ; } for ( int i = 0 ; i < q ; i ++ ) { if ( que [ i ] . type == 1 ) { while ( true ) { auto it = s . lower_bound ( que [ i ] . l ) ; if ( it == s . end ( ) * it > que [ i ] . r ) break ; que [ i ] . l = * it ; update ( * it , ( int ) sqrt ( arr [ * it ] ) - arr [ * it ] , n ) ; arr [ * it ] = ( int ) sqrt ( arr [ * it ] ) ; if ( arr [ * it ] == 1 ) s . erase ( * it ) ; que [ i ] . l ++ ; } } else { cout << ( sum ( que [ i ] . r ) - sum ( que [ i ] . l - 1 ) ) << endl ; } } } int main ( ) { int q = 4 ; int arr [ ] = { 0 , 4 , 5 , 1 , 2 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; queries que [ q + 1 ] ; que [ 0 ] . type = 2 , que [ 0 ] . l = 1 , que [ 0 ] . r = 5 ; que [ 1 ] . type = 1 , que [ 1 ] . l = 1 , que [ 1 ] . r = 2 ; que [ 2 ] . type = 1 , que [ 2 ] . l = 2 , que [ 2 ] . r = 4 ; que [ 3 ] . type = 2 , que [ 3 ] . l = 1 , que [ 3 ] . r = 5 ; answerQueries ( arr , que , n , q ) ; return 0 ; }
Number of pairs with Bitwise OR as Odd number | C ++ program to count pairs with odd OR ; Function to count pairs with odd OR ; find OR operation check odd or odd ; return count of odd pair ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int findOddPair ( int A [ ] , int N ) { int oddPair = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { if ( ( A [ i ] A [ j ] ) % 2 != 0 ) oddPair ++ ; } } return oddPair ; } int main ( ) { int A [ ] = { 5 , 6 , 2 , 8 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << findOddPair ( A , N ) << endl ; return 0 ; }
Count pairs with Bitwise XOR as EVEN number | C ++ program to count pairs with XOR giving a 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 print number of even pair
#include <iostream> NEW_LINE using namespace std ; int findevenPair ( int A [ ] , int N ) { int i , j ; int evenPair = 0 ; for ( i = 0 ; i < N ; i ++ ) { for ( j = i + 1 ; j < N ; j ++ ) { if ( ( A [ i ] ^ A [ j ] ) % 2 == 0 ) evenPair ++ ; } } return evenPair ; } int main ( ) { int A [ ] = { 5 , 4 , 7 , 2 , 1 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << findevenPair ( A , N ) << endl ; return 0 ; }
Count pairs with Bitwise XOR as EVEN number | C ++ program to count pairs with XOR giving a even number ; Function to count number of even pairs ; find all pairs ; return number of even pair ; Driver Code ; calling function findEvenPair and print number of even pair
#include <iostream> NEW_LINE using namespace std ; int findEvenPair ( int A [ ] , int N ) { int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] % 2 != 0 ) count ++ ; } int totalPairs = ( N * ( N - 1 ) / 2 ) ; int oddEvenPairs = count * ( N - count ) ; return totalPairs - oddEvenPairs ; } int main ( ) { int a [ ] = { 5 , 4 , 7 , 2 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << findEvenPair ( a , n ) << endl ; return 0 ; }
Count pairs with Bitwise | C ++ program to count pair with bitwise - AND as even number ; 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
#include <iostream> NEW_LINE using namespace std ; int findevenPair ( int A [ ] , int N ) { int i , j ; int evenPair = 0 ; for ( i = 0 ; i < N ; i ++ ) { for ( j = i + 1 ; j < N ; j ++ ) { if ( ( A [ i ] & A [ j ] ) % 2 == 0 ) evenPair ++ ; } } return evenPair ; } int main ( ) { int a [ ] = { 5 , 1 , 3 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << findevenPair ( a , n ) << endl ; return 0 ; }
Count pairs with Bitwise | C ++ program to count pair with bitwise - AND as even number ; Function to count number of pairs with EVEN bitwise AND ; count odd numbers ; count odd pairs ; return number of even pair ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int findevenPair ( int A [ ] , int N ) { int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) if ( A [ i ] % 2 != 0 ) count ++ ; int oddCount = count * ( count - 1 ) / 2 ; return ( N * ( N - 1 ) / 2 ) - oddCount ; } int main ( ) { int a [ ] = { 5 , 1 , 3 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << findevenPair ( a , n ) << endl ; return 0 ; }
Find a value whose XOR with given number is maximum | C ++ implementation of the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculate ( int X ) { int number_of_bits = 8 ; return ( ( 1 << number_of_bits ) - 1 ) ^ X ; } int main ( ) { int X = 4 ; cout << " Required ▁ Number ▁ is ▁ : ▁ " << calculate ( X ) << endl ; return 0 ; }
XOR of all elements of array with set bits equal to K | C ++ program to find Xor of all elements 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int xorGivenSetBits ( int arr [ ] , int n , int k ) { vector < int > v ; for ( int i = 0 ; i < n ; i ++ ) { if ( __builtin_popcount ( arr [ i ] ) == k ) { v . push_back ( arr [ i ] ) ; } } int result = v [ 0 ] ; for ( int i = 1 ; i < v . size ( ) ; i ++ ) result = result ^ v [ i ] ; return result ; } int main ( ) { int arr [ ] = { 2 , 13 , 1 , 19 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; cout << xorGivenSetBits ( arr , n , k ) ; return 0 ; }
Replace every element of the array with BitWise XOR of all other | C ++ program to Replace every element by the bitwise xor of all other elements ; 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 .
#include <bits/stdc++.h> NEW_LINE using namespace std ; void ReplaceElements ( int arr [ ] , int n ) { int X = 0 ; for ( int i = 0 ; i < n ; ++ i ) { X ^= arr [ i ] ; } for ( int i = 0 ; i < n ; ++ i ) { arr [ i ] = X ^ arr [ i ] ; } } int main ( ) { int arr [ ] = { 2 , 3 , 3 , 5 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; ReplaceElements ( arr , n ) ; for ( int i = 0 ; i < n ; ++ i ) { cout << arr [ i ] << " ▁ " ; } return 0 ; }
Find consecutive 1 s of length >= n in binary representation of a number | C ++ implementation of above approach ; Function to count the number of leading zeros ; Function to find the string of n consecutive 1 's ; Initialize position to return . ; Skip leading 0 's ; Set position after leading 0 's ; Count first group of 1 's. ; If length of consecutive 1 's is greater than or equal to n ; Not enough 1 's skip over to next group ; Update the position ; if no string is found ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countLeadingZeros ( int x ) { unsigned y ; int n ; n = 32 ; y = x >> 16 ; if ( y != 0 ) { n = n - 16 ; x = y ; } y = x >> 8 ; if ( y != 0 ) { n = n - 8 ; x = y ; } y = x >> 4 ; if ( y != 0 ) { n = n - 4 ; x = y ; } y = x >> 2 ; if ( y != 0 ) { n = n - 2 ; x = y ; } y = x >> 1 ; if ( y != 0 ) return n - 2 ; return n - x ; } int FindStringof1s ( unsigned x , int n ) { int k , p ; p = 0 ; while ( x != 0 ) { k = countLeadingZeros ( x ) ; x = x << k ; p = p + k ; k = countLeadingZeros ( ~ x ) ; if ( k >= n ) return p + 1 ; x = x << k ; p = p + k ; } return -1 ; } int main ( ) { int x = 35 ; int n = 2 ; cout << FindStringof1s ( x , n ) ; }
Assign other value to a variable from two possible values | CPP program to change value of x according to its current value . ; Function to alternate the values ; Main function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void alternate ( int & a , int & b , int & x ) { x = a ^ b ^ x ; } int main ( ) { int a = -10 ; int b = 15 ; int x = a ; cout << " x ▁ is ▁ : ▁ " << x ; alternate ( a , b , x ) ; cout << " After exchange " cout << " STRNEWLINE x ▁ is ▁ : ▁ " << x ; return 0 ; }
Number of leading zeros in binary representation of a given number | C ++ program of 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. ; Main function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countZeros ( unsigned int x ) { int total_bits = sizeof ( x ) * 8 ; int res = 0 ; while ( ! ( x & ( 1 << ( total_bits - 1 ) ) ) ) { x = ( x << 1 ) ; res ++ ; } return res ; } int main ( ) { int x = 101 ; cout << countZeros ( x ) ; return 0 ; }
Number of leading zeros in binary representation of a given number | C ++ program of number of leading zeros in binary representation of a given number ; Function to count the no . of leading zeros ; Main function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countZeros ( int x ) { unsigned y ; int n = 32 ; y = x >> 16 ; if ( y != 0 ) { n = n - 16 ; x = y ; } y = x >> 8 ; if ( y != 0 ) { n = n - 8 ; x = y ; } y = x >> 4 ; if ( y != 0 ) { n = n - 4 ; x = y ; } y = x >> 2 ; if ( y != 0 ) { n = n - 2 ; x = y ; } y = x >> 1 ; if ( y != 0 ) return n - 2 ; return n - x ; } int main ( ) { int x = 101 ; cout << countZeros ( x ) ; return 0 ; }
Comparing leading zeros in binary representations of two numbers | CPP program to find the number with more leading zeroes . ; Function to compare the no . of leading zeros ; if both have same no . of leading zeros ; if y has more leading zeros ; Main Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void LeadingZeros ( int x , int y ) { if ( ( x ^ y ) <= ( x & y ) ) cout << " Equal " else if ( ( x & ( ~ y ) ) > y ) cout << y ; else cout << x ; } int main ( ) { int x = 10 , y = 16 ; LeadingZeros ( x , y ) ; return 0 ; }
Count distinct Bitwise OR of all Subarrays | C ++ implementation of the above approach ; function to calculate count of distinct bitwise OR of all subarrays . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int distintBitwiseOR ( int arr [ ] , int n ) { unordered_set < int > ans , prev ; for ( int i = 0 ; i < n ; i ++ ) { unordered_set < int > ne ; for ( auto x : prev ) ne . insert ( arr [ i ] x ) ; ne . insert ( arr [ i ] ) ; for ( auto x : ne ) ans . insert ( x ) ; prev = ne ; } return ans . size ( ) ; } int main ( ) { int n = 3 ; int arr [ ] = { 1 , 2 , 4 } ; cout << distintBitwiseOR ( arr , n ) ; return 0 ; }
Printing all subsets of { 1 , 2 , 3 , ... n } without using array or loop | C ++ code to print all subsets of { 1 , 2 , 3 , n } without using array or loop , just recursion . ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void subset ( int , int , int ) ; void printSubsets ( int numOfBits , int num ) { if ( num >= 0 ) { cout << " { ▁ " ; subset ( numOfBits - 1 , num , numOfBits ) ; cout << " } " << endl ; printSubsets ( numOfBits , num - 1 ) ; } else return ; } void subset ( int nthBit , int num , int numOfBits ) { if ( nthBit >= 0 ) { if ( num & ( 1 << nthBit ) ) { cout << numOfBits - nthBit << " ▁ " ; } subset ( nthBit - 1 , num , numOfBits ) ; } else return ; } int main ( ) { int n = 4 ; printSubsets ( n , pow ( 2 , n ) - 1 ) ; }
Number of mismatching bits in the binary representation of two integers | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int A , int B ) { int count = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { if ( ( ( A >> i ) & 1 ) != ( ( B >> i ) & 1 ) ) { count ++ ; } } cout << " Number ▁ of ▁ different ▁ bits ▁ : ▁ " << count << endl ; } int main ( ) { int A = 12 , B = 15 ; solve ( A , B ) ; return 0 ; }
Set the rightmost off bit | CPP program to set the rightmost unset bit ; If all bits are set ; Set rightmost 0 bit ; Driver program to test above
#include <iostream> NEW_LINE using namespace std ; int setRightmostUnsetBit ( int n ) { if ( ( n & ( n + 1 ) ) == 0 ) return n ; return n | ( n + 1 ) ; } int main ( ) { int n = 21 ; cout << setRightmostUnsetBit ( n ) ; return 0 ; }
Print the number of set bits in each node of a Binary Tree | CPP program to print the number of set bits in each node of the 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 __builtin_popcount ( ) ; Traverse Left Subtree ; Traverse Right Subtree ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * newNode ( int data ) { Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } void printSetBit ( Node * root ) { if ( root == NULL ) return ; cout << " Set ▁ bits ▁ in ▁ Node ▁ " << root -> data << " ▁ = ▁ " << __builtin_popcount ( root -> data ) << " STRNEWLINE " ; printSetBit ( root -> left ) ; printSetBit ( root -> right ) ; } int main ( ) { Node * root = newNode ( 16 ) ; root -> left = newNode ( 13 ) ; root -> left -> left = newNode ( 14 ) ; root -> left -> right = newNode ( 12 ) ; root -> right = newNode ( 11 ) ; root -> right -> left = newNode ( 10 ) ; root -> right -> right = newNode ( 16 ) ; printSetBit ( root ) ; return 0 ; }
Find bitwise AND ( & ) of all possible sub | C ++ program to find of all the sub - arrays ; function to return AND of sub - arrays ; Driver program ; size of the array ; print and of all subarrays
#include <bits/stdc++.h> NEW_LINE using namespace std ; int AND ( int a [ ] , int n ) { int ans = a [ 0 ] ; for ( int i = 0 ; i < n ; ++ i ) ans &= a [ i ] ; return ans ; } int main ( ) { int a [ ] = { 1 , 2 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << AND ( a , n ) ; return 0 ; }
2 's complement for a givin string using XOR | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string TwoscomplementbyXOR ( string str ) { int n = str . length ( ) ; bool check_bit = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == '0' && check_bit == 0 ) { continue ; } else { if ( check_bit == 1 ) str [ i ] = ( str [ i ] - '0' ) ^ 1 + '0' ; check_bit = 1 ; } } if ( check_bit == 0 ) return "1" + str ; else return str ; } int main ( ) { string str = "101" ; cout << TwoscomplementbyXOR ( str ) ; return 0 ; }
Check whether bits are in alternate pattern in the given range | Set | C ++ implementation to check whether bits are in alternate pattern in the given range ; 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 program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isKthBitSet ( unsigned int n , unsigned int k ) { if ( ( n >> ( k - 1 ) ) & 1 ) return true ; return false ; } unsigned int setKthBit ( unsigned int n , unsigned int k ) { return ( ( 1 << ( k - 1 ) ) n ) ; } bool allBitsAreSet ( unsigned int n ) { if ( ( ( n + 1 ) & n ) == 0 ) return true ; return false ; } bool bitsAreInAltOrder ( unsigned int n ) { unsigned int num = n ^ ( n >> 1 ) ; return allBitsAreSet ( num ) ; } bool bitsAreInAltPatrnInGivenRange ( unsigned int n , unsigned int l , unsigned int r ) { unsigned int num , left_shift ; if ( isKthBitSet ( n , r ) ) { num = n ; left_shift = r ; } else { num = setKthBit ( n , ( r + 1 ) ) ; left_shift = r + 1 ; } num = num & ( ( 1 << left_shift ) - 1 ) ; num = num >> ( l - 1 ) ; return bitsAreInAltOrder ( num ) ; } int main ( ) { unsigned int n = 18 ; unsigned int l = 1 , r = 3 ; if ( bitsAreInAltPatrnInGivenRange ( n , l , r ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Check whether bits are in alternate pattern in the given range | C ++ implementation to check whether bits are in alternate pattern in the given range ; function to check whether bits are in alternate pattern in the given range ; right shift n by ( l - 1 ) bits ; get the bit at the last position in ' num ' ; right shift ' num ' by 1 ; loop until there are bits in the given range ; get the bit at the last position in ' num ' ; if true , then bits are not in alternate pattern ; update ' prev ' ; right shift ' num ' by 1 ; bits are in alternate pattern in the given range ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool bitsAreInAltPatrnInGivenTRange ( unsigned int n , unsigned int l , unsigned int r ) { unsigned int num , prev , curr ; num = n >> ( l - 1 ) ; prev = num & 1 ; num = num >> 1 ; for ( int i = 1 ; i <= ( r - l ) ; i ++ ) { curr = num & 1 ; if ( curr == prev ) return false ; prev = curr ; num = num >> 1 ; } return true ; } int main ( ) { unsigned int n = 18 ; unsigned int l = 1 , r = 3 ; if ( bitsAreInAltPatrnInGivenTRange ( n , l , r ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Increment a number without using ++ or + | CPP program to increment an unsigned int using bitwise operators . ; function that increment the value . ; Invert bits and apply negative sign ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int increment ( unsigned int i ) { i = - ( ~ i ) ; return i ; } int main ( ) { int n = 3 ; cout << increment ( n ) ; return 0 ; }
First element greater than or equal to X in prefix sum of N numbers using Binary Lifting | CPP 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void MakePreSum ( int arr [ ] , int presum [ ] , int n ) { presum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) presum [ i ] = presum [ i - 1 ] + arr [ i ] ; } int BinaryLifting ( int presum [ ] , int n , int x ) { int pos = 0 ; int LOGN = log2 ( n ) ; if ( x <= presum [ 0 ] ) return 0 ; for ( int i = LOGN ; i >= 0 ; i -- ) { if ( pos + ( 1 << i ) < n && presum [ pos + ( 1 << i ) ] < x ) { pos += ( 1 << i ) ; } } return pos + 1 ; } int main ( ) { int arr [ ] = { 2 , 5 , 7 , 1 , 6 , 9 , 12 , 4 , 6 } ; int x = 8 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int presum [ n ] = { 0 } ; MakePreSum ( arr , presum , n ) ; cout << BinaryLifting ( presum , n , x ) ; return 0 ; }
Maximum sum by adding numbers with same number of set bits | C ++ program to find 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int bit_count ( int n ) { int count = 0 ; while ( n ) { count ++ ; n = n & ( n - 1 ) ; } return count ; } int maxsum ( int arr [ ] , int n ) { int bits [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { bits [ i ] = bit_count ( arr [ i ] ) ; } int sum [ 32 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { sum [ bits [ i ] ] += arr [ i ] ; } int maximum = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { maximum = max ( sum [ i ] , maximum ) ; } return maximum ; } int main ( ) { int arr [ ] = { 2 , 3 , 8 , 5 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxsum ( arr , n ) ; return 0 ; }
Sum of XOR of sum of all pairs in an array | CPP program to find XOR of pair sums . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int xorPairSum ( int ar [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum = sum ^ ar [ i ] ; return 2 * sum ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << xorPairSum ( arr , n ) ; return 0 ; }
Count pairs with Bitwise OR as Even number | C ++ program to count pairs with even OR ; Count total even numbers in array . ; return count of even pair ; Driver main
#include <iostream> NEW_LINE using namespace std ; int findEvenPair ( int A [ ] , int N ) { int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) if ( ! ( A [ i ] & 1 ) ) count ++ ; return count * ( count - 1 ) / 2 ; } int main ( ) { int A [ ] = { 5 , 6 , 2 , 8 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << findEvenPair ( A , N ) << endl ; return 0 ; }
Check whether all the bits are unset in the given range | C ++ implementation to check whether all the bits are unset in the given range or not ; 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 program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool allBitsSetInTheGivenRange ( unsigned int n , unsigned int l , unsigned int r ) { int num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; int new_num = n & num ; if ( new_num == 0 ) return true ; return false ; } int main ( ) { unsigned int n = 17 ; unsigned int l = 2 , r = 4 ; if ( allBitsSetInTheGivenRange ( n , l , r ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Check if a number has same number of set and unset bits | C ++ program to 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkSame ( int n ) { int set = 0 , unset = 0 ; while ( n ) { if ( n & 1 ) set ++ ; else unset ++ ; n = n >> 1 ; } if ( set == unset ) return true ; else return false ; } int main ( ) { int n = 12 ; if ( checkSame ( n ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
Check if concatenation of two strings is balanced or not | CPP program to check if sequence obtained by concatenating two bracket sequences 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 .
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isBalanced ( string s ) { stack < char > st ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' ( ' ) st . push ( s [ i ] ) ; else { if ( st . empty ( ) ) { return false ; } else st . pop ( ) ; } } if ( ! st . empty ( ) ) return false ; return true ; } bool isBalancedSeq ( string s1 , string s2 ) { if ( isBalanced ( s1 + s2 ) ) return true ; return isBalanced ( s2 + s1 ) ; } int main ( ) { string s1 = " ) ( ) ( ( ) ) ) ) " ; string s2 = " ( ( ) ( ( ) ( " ; if ( isBalancedSeq ( s1 , s2 ) ) cout << " Balanced " ; else cout << " Not ▁ Balanced " ; return 0 ; }
Find iΓ’ €ℒ th index character in a binary string obtained after n iterations | Set 2 | C ++ program to find iaTMth Index character in a binary string obtained after n iterations ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void KthCharacter ( int m , int n , int k ) { int distance = pow ( 2 , n ) ; int Block_number = k / distance ; int remaining = k % distance ; int s [ 32 ] , x = 0 ; for ( ; m > 0 ; x ++ ) { s [ x ] = m % 2 ; m = m / 2 ; } int root = s [ x - 1 - Block_number ] ; if ( remaining == 0 ) { cout << root << endl ; return ; } bool flip = true ; while ( remaining > 1 ) { if ( remaining & 1 ) { flip = ! flip ; } remaining = remaining >> 1 ; } if ( flip ) { cout << ! root << endl ; } else { cout << root << endl ; } } int main ( ) { int m = 5 , k = 5 , n = 3 ; KthCharacter ( m , n , k ) ; return 0 ; }
Check whether the number has only first and last bits set | Set 2 | C ++ to check whether the number has only first and last bits set ; function to check whether the number has only first and last bits set ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool onlyFirstAndLastAreSet ( unsigned int n ) { if ( n == 1 ) return true ; if ( n == 2 ) return false ; return ( ( ( n - 1 ) & ( n - 2 ) ) == 0 ) ; } int main ( ) { unsigned int n = 9 ; if ( onlyFirstAndLastAreSet ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Number with set bits only between L | CPP 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getInteger ( int L , int R ) { int number = 0 ; for ( int i = L ; i <= R ; i ++ ) number += pow ( 2 , i ) ; return number ; } int main ( ) { int L = 2 , R = 5 ; cout << getInteger ( L , R ) ; return 0 ; }
Number with set bits only between L | CPP program to print the integer with all the bits set in range L - R Efficient Approach ; Function to return the integer with all the bits set in range L - R ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int setbitsfromLtoR ( int L , int R ) { return ( 1 << ( R + 1 ) ) - ( 1 << L ) ; } int main ( ) { int L = 2 , R = 5 ; cout << setbitsfromLtoR ( L , R ) ; return 0 ; }
XOR of Sum of every possible pair of an array | C ++ program to find XOR of sum of every possible pairs in an array ; Function to find XOR of sum of all pairs ; Calculate xor of all the elements ; Return twice of xor value ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findXor ( int arr [ ] , int n ) { int xoR = 0 ; for ( int i = 0 ; i < n ; i ++ ) { xoR = xoR ^ arr [ i ] ; } return xoR * 2 ; } int main ( ) { int arr [ 3 ] = { 1 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findXor ( arr , n ) ; return 0 ; }
Largest set with bitwise OR equal to n | CPP Program to find the 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void setBitwiseORk ( int n ) { vector < int > v ; for ( int i = 0 ; i <= n ; i ++ ) { if ( ( i n ) == n ) v . push_back ( i ) ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) cout << v [ i ] << ' ▁ ' ; } int main ( ) { int n = 5 ; setBitwiseORk ( n ) ; return 0 ; }
Two odd occurring elements in an array where all other occur even times | CPP 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printOdds ( int arr [ ] , int n ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) res = res ^ arr [ i ] ; int set_bit = res & ( ~ ( res - 1 ) ) ; int x = 0 , y = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] & set_bit ) x = x ^ arr [ i ] ; else y = y ^ arr [ i ] ; } cout << x << " ▁ " << y ; } int main ( ) { int arr [ ] = { 2 , 3 , 3 , 4 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printOdds ( arr , n ) ; return 0 ; }
Maximum subset with bitwise OR equal to k | CPP Program to find the 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void subsetBitwiseORk ( int arr [ ] , int n , int k ) { vector < int > v ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] k ) == k ) v . push_back ( arr [ i ] ) ; } int ans = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) ans |= v [ i ] ; if ( ans != k ) { cout << " Subset ▁ does ▁ not ▁ exist " << endl ; return ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) cout << v [ i ] << ' ▁ ' ; } int main ( ) { int k = 3 ; int arr [ ] = { 1 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; subsetBitwiseORk ( arr , n , k ) ; return 0 ; }
Number whose XOR sum with given array is a given number k | CPP Program to find the number whose XOR sum with given array is equal to 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 to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findEletobeInserted ( int A [ ] , int n , int k ) { int ans = k ; for ( int i = 0 ; i < n ; i ++ ) return ans ; } int main ( ) { int A [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int k = 10 ; cout << findEletobeInserted ( A , n , k ) << " ▁ has ▁ to ▁ be ▁ inserted " " ▁ in ▁ the ▁ given ▁ array ▁ to ▁ make ▁ xor ▁ sum ▁ of ▁ " << k << endl ; return 0 ; }
Left Shift and Right Shift Operators in C / C ++ | C ++ Program to demonstrate use of right shift operator ; a = 5 ( 00000101 ) , b = 9 ( 00001001 ) ; The result is 00000010 ; The result is 00000100
#include <iostream> NEW_LINE using namespace std ; int main ( ) { unsigned char a = 5 , b = 9 ; cout << " a > > 1 ▁ = ▁ " << ( a >> 1 ) << endl ; cout << " b > > 1 ▁ = ▁ " << ( b >> 1 ) << endl ; return 0 ; }
Left Shift and Right Shift Operators in C / C ++ | ; shift y by 61 bits left
#include <iostream> NEW_LINE using namespace std ; int main ( ) { int x = 19 ; unsigned long long y = 19 ; cout << " x ▁ < < ▁ 1 ▁ = ▁ " << ( x << 1 ) << endl ; cout << " x ▁ > > ▁ 1 ▁ = ▁ " << ( x >> 1 ) << endl ; cout << " y ▁ < < ▁ 61 ▁ = ▁ " << ( y << 61 ) << endl ; return 0 ; }
Left Shift and Right Shift Operators in C / C ++ |
#include <iostream> NEW_LINE using namespace std ; int main ( ) { int i = 3 ; cout << " pow ( 2 , ▁ " << i << " ) ▁ = ▁ " << ( 1 << i ) << endl ; i = 4 ; cout << " pow ( 2 , ▁ " << i << " ) ▁ = ▁ " << ( 1 << i ) << endl ; return 0 ; }
Range query for count of set bits | C ++ program to Range query for Count number 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int BitCount [ 10000 ] = { 0 } ; void fillSetBitsMatrix ( int arr [ ] , int n ) { for ( int i = 0 ; i < 32 ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { long temp = arr [ j ] >> i ; if ( temp % 2 != 0 ) BitCount [ j ] += 1 ; } } for ( int i = 1 ; i < n ; i ++ ) BitCount [ i ] += BitCount [ i - 1 ] ; } void Query ( int Q [ ] [ 2 ] , int q ) { for ( int i = 0 ; i < q ; i ++ ) cout << ( BitCount [ Q [ i ] [ 1 ] ] - BitCount [ Q [ i ] [ 0 ] - 1 ] ) << endl ; } int main ( ) { int Arr [ ] = { 1 , 5 , 6 , 10 , 9 , 4 , 67 } ; int n = sizeof ( Arr ) / sizeof ( Arr [ 0 ] ) ; fillSetBitsMatrix ( Arr , n ) ; int q = 2 ; int Q [ 2 ] [ 2 ] = { { 1 , 5 } , { 2 , 6 } } ; Query ( Q , q ) ; return 0 ; }
Generate n | C ++ program to generate n - bit gray codes ; 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 ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void decimalToBinaryNumber ( int x , int n ) { int * binaryNumber = new int ( x ) ; int i = 0 ; while ( x > 0 ) { binaryNumber [ i ] = x % 2 ; x = x / 2 ; i ++ ; } for ( int j = 0 ; j < n - i ; j ++ ) cout << '0' ; for ( int j = i - 1 ; j >= 0 ; j -- ) cout << binaryNumber [ j ] ; } void generateGrayarr ( int n ) { int N = 1 << n ; for ( int i = 0 ; i < N ; i ++ ) { int x = i ^ ( i >> 1 ) ; decimalToBinaryNumber ( x , n ) ; cout << endl ; } } int main ( ) { int n = 3 ; generateGrayarr ( n ) ; return 0 ; }
Sum of bitwise AND of all possible subsets of given set | C ++ 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 . ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define BITS 32 NEW_LINE int andSum ( int arr [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < BITS ; i ++ ) { int countSetBits = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] & ( 1 << i ) ) countSetBits ++ ; } int subset = ( 1 << countSetBits ) - 1 ; subset = ( subset * ( 1 << i ) ) ; ans += subset ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << andSum ( arr , size ) ; return 0 ; }
Maximize the number by rearranging bits | An efficient C ++ 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 function .
#include <bits/stdc++.h> NEW_LINE #define ll unsigned int NEW_LINE using namespace std ; ll maximize ( ll a ) { ll n = _popcnt32 ( a ) ; if ( n == 32 ) return a ; ll res = ( 1 << n ) - 1 ; return ( res << ( 32 - n ) ) ; } int main ( ) { ll a = 3 ; cout << maximize ( a ) << endl ; return 0 ; }
Minimum number using set bits of a given number | An efficient C ++ program to find minimum number formed by 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 function .
#include <bits/stdc++.h> NEW_LINE #define ll unsigned int NEW_LINE using namespace std ; ll minimize ( ll a ) { ll n = _popcnt32 ( a ) ; return ( pow ( 2 , n ) - 1 ) ; } int main ( ) { ll a = 11 ; cout << minimize ( a ) << endl ; return 0 ; }
Disjoint Set Union on trees | Set 2 | CPP code to find maximum possible cost ; Edge structure ; v : Adjacency list representation of Graph p : stores parents of nodes ; Weighted union - find with path compression ; DFS is called to generate parent of a node from adjacency list representation ; Utility function for Union ; Fixed ' i ' as AND ; Generating supermasks of ' i ' ; Checking whether p [ x ] is also a supermask of i . ; Keep track of maximum size of subtree ; Storing maximum cost of subtree with a given AND ; Separating components which are merged during Union operation for next AND value . ; Driver code ; Number of nodes ; Taking edges as input and put them in adjacency list representation ; Initializing parent vertex of '1' as '1' ; Call DFS to generate ' p ' array
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100010 NEW_LINE struct Edge { int u , v ; } ; vector < int > v [ N ] ; int p [ N ] ; struct wunionfind { int id [ N ] , sz [ N ] ; void initial ( int n ) { for ( int i = 1 ; i <= n ; i ++ ) id [ i ] = i , sz [ i ] = 1 ; } int Root ( int idx ) { int i = idx ; while ( i != id [ i ] ) id [ i ] = id [ id [ i ] ] , i = id [ i ] ; return i ; } void Union ( int a , int b ) { int i = Root ( a ) , j = Root ( b ) ; if ( i != j ) { if ( sz [ i ] >= sz [ j ] ) { id [ j ] = i , sz [ i ] += sz [ j ] ; sz [ j ] = 0 ; } else { id [ i ] = j , sz [ j ] += sz [ i ] ; sz [ i ] = 0 ; } } } } ; wunionfind W ; void dfs ( int u , int parent ) { for ( int i = 0 ; i < v [ u ] . size ( ) ; i ++ ) { int j = v [ u ] [ i ] ; if ( j != parent ) { p [ j ] = u ; dfs ( j , u ) ; } } } int UnionUtil ( int n ) { int ans = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int maxi = 1 ; for ( int x = i ; x <= n ; x = ( i | ( x + 1 ) ) ) { int y = p [ x ] ; if ( ( y & i ) == i ) { W . Union ( x , y ) ; maxi = max ( maxi , W . sz [ W . Root ( x ) ] ) ; } } ans = max ( ans , maxi * i ) ; for ( int x = i ; x <= n ; x = ( i | ( x + 1 ) ) ) { W . sz [ x ] = 1 ; W . id [ x ] = x ; } } return ans ; } int main ( ) { int n , i ; n = 6 ; W . initial ( n ) ; Edge e [ ] = { { 1 , 2 } , { 2 , 3 } , { 3 , 4 } , { 3 , 5 } , { 5 , 6 } } ; int q = sizeof ( e ) / sizeof ( e [ 0 ] ) ; for ( i = 0 ; i < q ; i ++ ) { int x , y ; x = e [ i ] . u , y = e [ i ] . v ; v [ x ] . push_back ( y ) ; v [ y ] . push_back ( x ) ; } p [ 1 ] = 1 ; dfs ( 1 , -1 ) ; int ans = UnionUtil ( n ) ; printf ( " Maximum ▁ Cost ▁ = ▁ % d STRNEWLINE " , ans ) ; return 0 ; }
Maximum steps to transform 0 to X with bitwise AND | CPP code to find the maximum possible effort ; Function to get no of set bits in binary representation of positive integer n ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned int countSetBits ( unsigned int n ) { unsigned int count = 0 ; while ( n ) { count += n & 1 ; n >>= 1 ; } return count ; } int main ( ) { int i = 3 ; cout << countSetBits ( i ) ; return 0 ; }
Check a number is odd or even without modulus operator | A simple C ++ program to check for even or odd ; Returns true if n is even , else odd ; Driver code
#include <iostream> NEW_LINE using namespace std ; bool isEven ( int n ) { bool isEven = true ; for ( int i = 1 ; i <= n ; i ++ ) isEven = ! isEven ; return isEven ; } int main ( ) { int n = 101 ; isEven ( n ) ? cout << " Even " : cout << " Odd " ; return 0 ; }
Check a number is odd or even without modulus operator | A simple C ++ program to check for even or odd ; Returns true if n is even , else odd ; Return true if n / 2 does not result in a float value . ; Driver code
#include <iostream> NEW_LINE using namespace std ; bool isEven ( int n ) { return ( ( n / 2 ) * 2 == n ) ; } int main ( ) { int n = 101 ; isEven ( n ) ? cout << " Even " : cout << " Odd " ; return 0 ; }
Count pairs in an array which have at least one digit common | CPP Program to count pairs in an array with some common digit ; 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 to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkValidPair ( int num1 , int num2 ) { string s1 = to_string ( num1 ) ; string s2 = to_string ( num2 ) ; for ( int i = 0 ; i < s1 . size ( ) ; i ++ ) for ( int j = 0 ; j < s2 . size ( ) ; j ++ ) if ( s1 [ i ] == s2 [ j ] ) return true ; return false ; } int countPairs ( int arr [ ] , int n ) { int numberOfPairs = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( checkValidPair ( arr [ i ] , arr [ j ] ) ) numberOfPairs ++ ; return numberOfPairs ; } int main ( ) { int arr [ ] = { 10 , 12 , 24 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , n ) << endl ; return 0 ; }
Check if bitwise AND of any subset is power of two | CPP 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int NUM_BITS = 32 ; bool isPowerOf2 ( int num ) { return ( num && ! ( num & ( num - 1 ) ) ) ; } bool checkSubsequence ( int arr [ ] , int n ) { if ( n == 1 ) return isPowerOf2 ( arr [ 0 ] ) ; int total = 0 ; for ( int i = 0 ; i < NUM_BITS ; i ++ ) total = total | ( 1 << i ) ; for ( int i = 0 ; i < NUM_BITS ; i ++ ) { int ans = total ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] & ( 1 << i ) ) ans = ans & arr [ j ] ; } if ( isPowerOf2 ( ans ) ) return true ; } return false ; } int main ( ) { int arr [ ] = { 12 , 13 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkSubsequence ( arr , n ) ) printf ( " YES STRNEWLINE " ) ; else printf ( " NO STRNEWLINE " ) ; return 0 ; }
Levelwise Alternating OR and XOR operations in Segment Tree | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMid ( int s , int e ) { return s + ( e - s ) / 2 ; } void constructSTUtil ( int arr [ ] , int ss , int se , int * st , int si , int operation ) { if ( ss == se ) { st [ si ] = arr [ ss ] ; return ; } int mid = getMid ( ss , se ) ; constructSTUtil ( arr , ss , mid , st , si * 2 + 1 , ! operation ) ; constructSTUtil ( arr , mid + 1 , se , st , si * 2 + 2 , ! operation ) ; if ( operation == 1 ) { st [ si ] = ( st [ 2 * si + 1 ] st [ 2 * si + 2 ] ) ; } else { st [ si ] = ( st [ 2 * si + 1 ] ^ st [ 2 * si + 2 ] ) ; } } int * constructST ( int arr [ ] , int n ) { int x = ( int ) ( ceil ( log2 ( n ) ) ) ; int max_size = 2 * ( int ) pow ( 2 , x ) - 1 ; int * st = new int [ max_size ] ; int operationAtRoot = ( x % 2 == 0 ? 0 : 1 ) ; constructSTUtil ( arr , 0 , n - 1 , st , 0 , operationAtRoot ) ; return st ; } int main ( ) { int leaves [ ] = { 1 , 6 , 3 , 7 , 5 , 9 , 10 , 4 } ; int n = sizeof ( leaves ) / sizeof ( leaves [ 0 ] ) ; int * segmentTree = constructST ( leaves , n ) ; int rootIndex = 0 ; cout << " Value ▁ at ▁ Root ▁ Node ▁ = ▁ " << segmentTree [ rootIndex ] ; }
Leftover element after performing alternate Bitwise OR and Bitwise XOR operations on adjacent pairs | CPP 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 1000 NEW_LINE int lastElement ( int a [ ] , int n ) { int steps = 1 ; vector < int > v [ N ] ; if ( n == 1 ) return a [ 0 ] ; for ( int i = 0 ; i < n ; i += 2 ) v [ steps ] . push_back ( a [ i ] a [ i + 1 ] ) ; while ( v [ steps ] . size ( ) > 1 ) { steps += 1 ; for ( int i = 0 ; i < v [ steps - 1 ] . size ( ) ; i += 2 ) { if ( steps & 1 ) v [ steps ] . push_back ( v [ steps - 1 ] [ i ] v [ steps - 1 ] [ i + 1 ] ) ; v [ steps ] . push_back ( v [ steps - 1 ] [ i ] ^ v [ steps - 1 ] [ i + 1 ] ) ; } } return v [ steps ] [ 0 ] ; } int main ( ) { int a [ ] = { 1 , 4 , 5 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int index = 0 ; int value = 2 ; a [ 0 ] = 2 ; cout << lastElement ( a , n ) << endl ; index = 3 ; value = 5 ; a [ index ] = value ; cout << lastElement ( a , n ) << endl ; return 0 ; }
Find the winner in nim | CPP to find nim - game winner ; function to find winner of NIM - game ; case when Alice is winner ; when Bob is winner ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; string findWinner ( int A [ ] , int n ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) res ^= A [ i ] ; if ( res == 0 n % 2 == 0 ) return " Alice " ; else return " Bob " ; } int main ( ) { int A [ ] = { 1 , 4 , 3 , 5 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << " Winner ▁ = ▁ " << findWinner ( A , n ) ; return 0 ; }
Fibbinary Numbers ( No consecutive 1 s in binary ) | C ++ implementation to check whether a number is fibbinary or not ; 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 program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isFibbinaryNum ( unsigned int n ) { if ( ( n & ( n >> 1 ) ) == 0 ) return true ; return false ; } int main ( ) { unsigned int n = 10 ; if ( isFibbinaryNum ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Maximum XOR | Program to obtain maximum XOR value sub - array ; function to calculate maximum XOR value ; Return ( 2 ^ c - 1 ) ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxXOR ( int n , int k ) { int c = log2 ( n ) + 1 ; return ( ( 1 << c ) - 1 ) ; } int main ( ) { int n = 12 ; int k = 3 ; cout << maxXOR ( n , k ) ; return 0 ; }
Divide two integers without using multiplication , division and mod operator | C ++ implementation to 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 only iff either one of them is negative 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int divide ( long long dividend , long long divisor ) { int sign = ( ( dividend < 0 ) ^ ( divisor < 0 ) ) ? -1 : 1 ; dividend = abs ( dividend ) ; divisor = abs ( divisor ) ; long long quotient = 0 , temp = 0 ; for ( int i = 31 ; i >= 0 ; -- i ) { if ( temp + ( divisor << i ) <= dividend ) { temp += divisor << i ; quotient |= 1LL << i ; } } if ( sign == -1 ) quotient = - quotient ; return quotient ; } int main ( ) { int a = 10 , b = 3 ; cout << divide ( a , b ) << " STRNEWLINE " ; a = 43 , b = -8 ; cout << divide ( a , b ) ; return 0 ; }
XOR of two numbers after making length of their binary representations equal | C ++ implementation to return XOR of two numbers after making length of their binary representation same ; 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 to check the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( int n ) { int c = 0 ; while ( n ) { c ++ ; n = n >> 1 ; } return c ; } int XOR ( int a , int b ) { int c = min ( a , b ) ; int d = max ( a , b ) ; if ( count ( c ) < count ( d ) ) c = c << ( count ( d ) - count ( c ) ) ; return ( c ^ d ) ; } int main ( ) { int a = 13 , b = 5 ; cout << XOR ( a , b ) ; return 0 ; }
Check if binary string multiple of 3 using DFA | C ++ program to check if the binary string is divisible by 3. ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void CheckDivisibilty ( string A ) { int oddbits = 0 , evenbits = 0 ; for ( int counter = 0 ; counter < A . length ( ) ; counter ++ ) { if ( A [ counter ] == '1' ) { if ( counter % 2 == 0 ) { evenbits ++ ; } else { oddbits ++ ; } } } if ( abs ( oddbits - evenbits ) % 3 == 0 ) { cout << " Yes " << endl ; } else { cout << " No " << endl ; } } int main ( ) { string A = "10101" ; CheckDivisibilty ( A ) ; return 0 ; }
Swap every two bits in bytes | C ++ 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 to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned int swapBitsInPair ( unsigned int x ) { return ( ( x & 0b10101010 ) >> 1 ) | ( ( x & 0b01010101 ) << 1 ) ; } int main ( ) { unsigned int x = 4 ; cout << swapBitsInPair ( x ) ; return 0 ; }
Alternate bits of two numbers to create a new number | CPP Program to generate a number using alternate bits of two numbers . ; 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
#include <iostream> NEW_LINE using namespace std ; int setevenbits ( int n ) { int temp = n ; int count = 0 ; int res = 0 ; for ( temp = n ; temp > 0 ; temp >>= 1 ) { if ( count % 2 == 1 ) res |= ( 1 << count ) ; count ++ ; } return ( n & res ) ; } int setoddbits ( int m ) { int count = 0 ; int res = 0 ; for ( int temp = m ; temp > 0 ; temp >>= 1 ) { if ( count % 2 == 0 ) res |= ( 1 << count ) ; count ++ ; } return ( m & res ) ; } int getAlternateBits ( int n , int m ) { int tempn = setevenbits ( n ) ; int tempm = setoddbits ( m ) ; return ( tempn tempm ) ; } int main ( ) { int n = 10 ; int m = 11 ; cout << getAlternateBits ( n , m ) ; return 0 ; }
Decimal representation of given binary string is divisible by 20 or not | C ++ implementation to check whether decimal representation of given binary number is divisible by 20 or not ; function to check whether decimal representation of given binary number is divisible by 10 or not ; if last digit is '1' , then number is not divisible by 10 ; to accumulate the sum of last digits in perfect powers of 2 ; traverse from the 2 nd last up to 1 st digit in ' bin ' ; if digit in '1' ; calculate digit 's position from the right ; according to the digit 's position, obtain the last digit of the applicable perfect power of 2 ; if last digit is 0 , then divisible by 10 ; not divisible by 10 ; function to check whether decimal representation of given binary number is divisible by 20 or not ; if ' bin ' is an odd number ; check if bin ( 0. . n - 2 ) is divisible by 10 or not ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isDivisibleBy10 ( char bin [ ] , int n ) { if ( bin [ n - 1 ] == '1' ) return false ; int sum = 0 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( bin [ i ] == '1' ) { int posFromRight = n - i - 1 ; if ( posFromRight % 4 == 1 ) sum = sum + 2 ; else if ( posFromRight % 4 == 2 ) sum = sum + 4 ; else if ( posFromRight % 4 == 3 ) sum = sum + 8 ; else if ( posFromRight % 4 == 0 ) sum = sum + 6 ; } } if ( sum % 10 == 0 ) return true ; return false ; } bool isDivisibleBy20 ( char bin [ ] , int n ) { if ( bin [ n - 1 ] == '1' ) return false ; return isDivisibleBy10 ( bin , n - 1 ) ; } int main ( ) { char bin [ ] = "101000" ; int n = sizeof ( bin ) / sizeof ( bin [ 0 ] ) ; if ( isDivisibleBy20 ( bin , n - 1 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
For every set bit of a number toggle bits of other | A CPP program toggle bits of n2 that are at same position as set bits of n1 . ; function for the Nega_bit ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int toggleBits ( int n1 , int n2 ) { return n1 ^ n2 ; } int main ( ) { int n1 = 2 , n2 = 5 ; cout << toggleBitst ( n1 , n2 ) << endl ; return 0 ; }
Toggle all even bits of a number | CPP code to Toggle all even bit 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
#include <iostream> NEW_LINE using namespace std ; int evenbittogglenumber ( int n ) { int res = 0 , count = 0 ; for ( int temp = n ; temp > 0 ; temp >>= 1 ) { if ( count % 2 == 1 ) res |= ( 1 << count ) ; count ++ ; } return n ^ res ; } int main ( ) { int n = 11 ; cout << evenbittogglenumber ( n ) ; return 0 ; }
Toggle first and last bits of a number | CPP program to 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
#include <iostream> NEW_LINE using namespace std ; int takeLandFsetbits ( int n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return ( ( n + 1 ) >> 1 ) + 1 ; } int toggleFandLbits ( int n ) { if ( n == 1 ) return 0 ; return n ^ takeLandFsetbits ( n ) ; } int main ( ) { int n = 10 ; cout << toggleFandLbits ( n ) ; return 0 ; }
Odious number | C / C ++ program to check if a number is Odious Number or not ; 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
#include <iostream> NEW_LINE using namespace std ; #include <math.h> NEW_LINE int countSetBits ( int n ) { unsigned int count = 0 ; while ( n ) { n &= ( n - 1 ) ; count ++ ; } return count ; } int checkOdious ( int n ) { return ( countSetBits ( n ) % 2 == 1 ) ; } int main ( ) { int num = 32 ; if ( checkOdious ( num ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Set the Left most unset bit | C ++ program to set the leftmost 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
#include <iostream> NEW_LINE using namespace std ; int setleftmostunsetbit ( int n ) { if ( ( n & ( n + 1 ) ) == 0 ) return n ; int pos = 0 ; for ( int temp = n , count = 0 ; temp > 0 ; temp >>= 1 , count ++ ) if ( ( temp & 1 ) == 0 ) pos = count ; return ( n | ( 1 << ( pos ) ) ) ; } int main ( ) { int n = 10 ; cout << setleftmostunsetbit ( n ) ; return 0 ; }
Maximum XOR using K numbers from 1 to n | CPP program to find max xor sum of 1 to n using atmost k numbers ; 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 program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxXorSum ( int n , int k ) { if ( k == 1 ) return n ; int res = 1 ; while ( res <= n ) res <<= 1 ; return res - 1 ; } int main ( ) { int n = 4 , k = 3 ; cout << maxXorSum ( n , k ) ; return 0 ; }
Increment a number by one by manipulating the bits | C ++ 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 to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getPosOfRightmostSetBit ( int n ) { return log2 ( n & - n ) ; } unsigned int toggleLastKBits ( unsigned int n , unsigned int k ) { unsigned int num = ( 1 << k ) - 1 ; return ( n ^ num ) ; } unsigned int incrementByOne ( unsigned int n ) { int k = getPosOfRightmostSetBit ( ~ n ) ; n = ( ( 1 << k ) n ) ; if ( k != 0 ) n = toggleLastKBits ( n , k ) ; return n ; } int main ( ) { unsigned int n = 15 ; cout << incrementByOne ( n ) ; return 0 ; }
XNOR of two numbers | CPP 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 xnornum ; to 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 code
#include <iostream> NEW_LINE using namespace std ; int xnor ( int a , int b ) { if ( a < b ) swap ( a , b ) ; if ( a == 0 && b == 0 ) return 1 ; int a_rem = 0 ; int b_rem = 0 ; int count = 0 ; int xnornum = 0 ; while ( a ) { a_rem = a & 1 ; b_rem = b & 1 ; if ( a_rem == b_rem ) xnornum |= ( 1 << count ) ; count ++ ; a = a >> 1 ; b = b >> 1 ; } return xnornum ; } int main ( ) { int a = 10 , b = 50 ; cout << xnor ( a , b ) ; return 0 ; }
XNOR of two numbers | CPP 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 ; if num2 is greater then we swap this number in num1 ; Driver code
#include <iostream> NEW_LINE using namespace std ; int togglebit ( int n ) { if ( n == 0 ) return 1 ; int i = n ; n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return i ^ n ; } int XNOR ( int num1 , int num2 ) { if ( num1 < num2 ) swap ( num1 , num2 ) ; num1 = togglebit ( num1 ) ; return num1 ^ num2 ; } int main ( ) { int num1 = 10 , num2 = 20 ; cout << XNOR ( num1 , num2 ) ; return 0 ; }
Maximum OR sum of sub | CPP program to find maximum OR sum ; function to find maximum OR sum ; OR sum of all the elements in both arrays ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void MaximumSum ( int a [ ] , int b [ ] , int n ) { int sum1 = 0 , sum2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum1 |= a [ i ] ; sum2 |= b [ i ] ; } cout << sum1 + sum2 << endl ; } int main ( ) { int A [ ] = { 1 , 2 , 4 , 3 , 2 } ; int B [ ] = { 2 , 3 , 3 , 12 , 1 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; MaximumSum ( A , B , n ) ; return 0 ; }
Position of rightmost bit with first carry in sum of two binary | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef unsigned long long int ull ; unsigned int posOfRightmostSetBit ( ull n ) { return log2 ( n & - n ) + 1 ; } unsigned int posOfCarryBit ( ull a , ull b ) { return posOfRightmostSetBit ( a & b ) ; } int main ( ) { ull a = 10 , b = 2 ; cout << posOfCarryBit ( a , b ) ; return 0 ; }
Check whether the two numbers differ at one bit position only | C ++ implementation to 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 program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPowerOfTwo ( unsigned int x ) { return x && ( ! ( x & ( x - 1 ) ) ) ; } bool differAtOneBitPos ( unsigned int a , unsigned int b ) { return isPowerOfTwo ( a ^ b ) ; } int main ( ) { unsigned int a = 13 , b = 9 ; if ( differAtOneBitPos ( a , b ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Multiplication with a power of 2 | Simple C / C ++ program to compute x * ( 2 ^ n ) ; Returns 2 raised to power n ; Driven program
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long int ll ; ll power2 ( ll n ) { if ( n == 0 ) return 1 ; if ( n == 1 ) return 2 ; return power2 ( n / 2 ) * power2 ( n / 2 ) ; } ll multiply ( ll x , ll n ) { return x * power2 ( n ) ; } int main ( ) { ll x = 70 , n = 2 ; cout << multiply ( x , n ) ; return 0 ; }
Multiplication with a power of 2 | Efficient C / C ++ program to compute x * ( 2 ^ n ) ; Driven program to check above function
#include <stdio.h> NEW_LINE typedef long long int ll ; ll multiply ( ll x , ll n ) { return x << n ; } int main ( ) { ll x = 70 , n = 2 ; printf ( " % lld " , multiply ( x , n ) ) ; return 0 ; }
Check if n is divisible by power of 2 without using arithmetic operators | C ++ implementation to check whether n is divisible by pow ( 2 , m ) ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isDivBy2PowerM ( unsigned int n , unsigned int m ) { if ( ( n & ( ( 1 << m ) - 1 ) ) == 0 ) return true ; return false ; } int main ( ) { unsigned int n = 8 , m = 2 ; if ( isDivBy2PowerM ( n , m ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Game of Nim with removal of one stone allowed | C ++ program for 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool findWinner ( int N ) { return N & 1 ; } int main ( ) { int N = 15 ; findWinner ( N ) ? ( cout << " Player ▁ A " ; ) : ( cout << " Player ▁ B " ; ) ; return 0 ; }
Toggle all odd bits of a number | Toggle all odd bit 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
#include <iostream> NEW_LINE using namespace std ; int evenbittogglenumber ( int n ) { int res = 0 , count = 0 ; for ( int temp = n ; temp > 0 ; temp >>= 1 ) { if ( count % 2 == 0 ) res |= ( 1 << count ) ; count ++ ; } return n ^ res ; } int main ( ) { int n = 11 ; cout << evenbittogglenumber ( n ) ; return 0 ; }
Quotient and remainder dividing by 2 ^ k ( a power of 2 ) | CPP 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void divide ( int n , int m ) { cout << " Remainder ▁ = ▁ " << ( ( n ) & ( m - 1 ) ) ; cout << " Quotient = " } int main ( ) { int n = 43 , m = 8 ; divide ( n , m ) ; return 0 ; }
Maximum AND value of a pair in an array | CPP Program to find maximum XOR value of a pair ; Function for finding maximum and value pair ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxAND ( int arr [ ] , int n ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) res = max ( res , arr [ i ] & arr [ j ] ) ; return res ; } int main ( ) { int arr [ ] = { 4 , 8 , 6 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Maximum ▁ AND ▁ Value ▁ = ▁ " << maxAND ( arr , n ) ; return 0 ; }
Check if a number is positive , negative or zero using bit operators | CPP program to find if a number is positive , negative or zero using bit wise 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
#include <iostream> NEW_LINE using namespace std ; int index ( int i ) { return 1 + ( i >> 31 ) - ( - i >> 31 ) ; } void check ( int n ) { string s [ ] = { " negative " , " zero " , " positive " } ; int val = index ( n ) ; cout << n << " ▁ is ▁ " << s [ val ] << endl ; } int main ( ) { check ( 30 ) ; check ( -20 ) ; check ( 0 ) ; return 0 ; }
Find two numbers from their sum and XOR | CPP program to find two numbers with given Sum and XOR such that value of first number is minimum . ; 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. ; We leave i - th bit of b as 0. ; else ( Xi == 1 && Ai == 1 ) ; Driver function
#include <iostream> NEW_LINE using namespace std ; void compute ( unsigned long int S , unsigned long int X ) { unsigned long int A = ( S - X ) / 2 ; int a = 0 , b = 0 ; for ( int i = 0 ; i < 8 * sizeof ( S ) ; i ++ ) { unsigned long int Xi = ( X & ( 1 << i ) ) ; unsigned long int Ai = ( A & ( 1 << i ) ) ; if ( Xi == 0 && Ai == 0 ) { } else if ( Xi == 0 && Ai > 0 ) { a = ( ( 1 << i ) a ) ; b = ( ( 1 << i ) b ) ; } else if ( Xi > 0 && Ai == 0 ) { a = ( ( 1 << i ) a ) ; } { cout << " Not ▁ Possible " ; return ; } } cout << " a ▁ = ▁ " << a << endl << " b ▁ = ▁ " << b ; } int main ( ) { unsigned long int S = 17 , X = 13 ; compute ( S , X ) ; return 0 ; }
Divisibility by 64 with removal of bits allowed | CPP program to find if given binary string can become divisible by 64 after removing some bits . ; function to check if it is possible to make it a multiple of 64. ; counter to count 0 's ; length of the string ; loop which traverses right to left and calculates the number of zeros before 1. ; driver code
#include <iostream> NEW_LINE using namespace std ; bool checking ( string s ) { int c = 0 ; int n = s . length ( ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( s [ i ] == '0' ) c ++ ; if ( c >= 6 and s [ i ] == '1' ) return true ; } return false ; } int main ( ) { string s = "100010001" ; if ( checking ( s ) ) cout << " Possible " ; else cout << " Not ▁ possible " ; return 0 ; }
Modify a bit at a given position | CPP program to modify a bit at position p in n to b . ; Returns modified n . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int modifyBit ( int n , int p , int b ) { int mask = 1 << p ; return ( ( n & ~ mask ) | ( b << p ) ) ; } int main ( ) { cout << modifyBit ( 6 , 2 , 0 ) << endl ; cout << modifyBit ( 6 , 5 , 1 ) << endl ; return 0 ; }
Count set bits in a range | C ++ implementation to count set bits in the given 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned int countSetBits ( int n ) { unsigned int count = 0 ; while ( n ) { n &= ( n - 1 ) ; count ++ ; } return count ; } unsigned int countSetBitsInGivenRange ( unsigned int n , unsigned int l , unsigned int r ) { int num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; return countSetBits ( n & num ) ; } int main ( ) { unsigned int n = 42 ; unsigned int l = 2 , r = 5 ; cout << countSetBitsInGivenRange ( n , l , r ) ; return 0 ; }
Check if one of the numbers is one 's complement of the other | C ++ implementation to check if one of the two 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 to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool areAllBitsSet ( unsigned int n ) { if ( n == 0 ) return false ; if ( ( ( n + 1 ) & n ) == 0 ) return true ; return false ; } bool isOnesComplementOfOther ( unsigned int a , unsigned int b ) { return areAllBitsSet ( a ^ b ) ; } int main ( ) { unsigned int a = 10 , b = 5 ; if ( isOnesComplementOfOther ( a , b ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Unique element in an array where all elements occur k times except one | CPP program to find unique element where every element appears k times except one ; Create a count array to store count of numbers that have a particular bit set . count [ i ] stores count of array elements with i - th bit set . ; AND ( bitwise ) each element of the array with each set digit ( one at a time ) to get the count of set bits at each position ; Now consider all bits whose count is not multiple of k to form the required number . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findUnique ( unsigned int a [ ] , int n , int k ) { int INT_SIZE = 8 * sizeof ( unsigned int ) ; int count [ INT_SIZE ] ; memset ( count , 0 , sizeof ( count ) ) ; for ( int i = 0 ; i < INT_SIZE ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( ( a [ j ] & ( 1 << i ) ) != 0 ) count [ i ] += 1 ; unsigned res = 0 ; for ( int i = 0 ; i < INT_SIZE ; i ++ ) res += ( count [ i ] % k ) * ( 1 << i ) ; return res ; } int main ( ) { unsigned int a [ ] = { 6 , 2 , 5 , 2 , 2 , 6 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 3 ; cout << findUnique ( a , n , k ) ; return 0 ; }
Check whether the number has only first and last bits set | C ++ to check whether the number has only first and last bits set ; function to check whether ' n ' is a power of 2 or not ; function to check whether the number has only first and last bits set ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool powerOfTwo ( unsigned int n ) { return ( ! ( n & n - 1 ) ) ; } bool onlyFirstAndLastAreSet ( unsigned int n ) { if ( n == 1 ) return true ; if ( n == 2 ) return false ; return powerOfTwo ( n - 1 ) ; } int main ( ) { unsigned int n = 9 ; if ( onlyFirstAndLastAreSet ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Check if a number has bits in alternate pattern | Set | C ++ implementation to check if a number has bits in alternate pattern ; 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 ' ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool allBitsAreSet ( unsigned int n ) { if ( ( ( n + 1 ) & n ) == 0 ) return true ; return false ; } bool bitsAreInAltOrder ( unsigned int n ) { unsigned int num = n ^ ( n >> 1 ) ; return allBitsAreSet ( num ) ; } int main ( ) { unsigned int n = 10 ; if ( bitsAreInAltOrder ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Minimum flips required to maximize a number with k set bits | CPP for finding min flip for maximizing given n ; function for finding set bit ; return count of set bit ; function for finding min flip ; number of bits in n ; Find the largest number of same size with k set bits ; Count bit differences to find required flipping . ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int setBit ( int xorValue ) { int count = 0 ; while ( xorValue ) { if ( xorValue % 2 ) count ++ ; xorValue /= 2 ; } return count ; } int minFlip ( int n , int k ) { int size = log2 ( n ) + 1 ; int max = pow ( 2 , k ) - 1 ; max = max << ( size - k ) ; int xorValue = ( n ^ max ) ; return ( setBit ( xorValue ) ) ; } int main ( ) { int n = 27 , k = 3 ; cout << " Min ▁ Flips ▁ = ▁ " << minFlip ( n , k ) ; return 0 ; }
Set all the bits in given range of a number | C ++ implementation to Set bits in the given range ; function to toggle bits in the given range ; calculating a number ' range ' having set bits in the range from l to r and all other bits as 0 ( or unset ) . ; Driver code
#include <iostream> NEW_LINE using namespace std ; int setallbitgivenrange ( int n , int l , int r ) { int range = ( ( ( 1 << ( l - 1 ) ) - 1 ) ^ ( ( 1 << ( r ) ) - 1 ) ) ; return ( n range ) ; } int main ( ) { int n = 17 , l = 2 , r = 3 ; cout << setallbitgivenrange ( n , l , r ) ; return 0 ; }
Count total bits in a number | C ++ program to find total bit in given number ; log function in base 2 take only integer part ; Driven program
#include <iostream> NEW_LINE #include <cmath> NEW_LINE unsigned countBits ( unsigned int number ) { return ( int ) log2 ( number ) + 1 ; } int main ( ) { unsigned int num = 65 ; std :: cout << countBits ( num ) << ' ' ; return 0 ; }
Check whether all the bits are unset in the given range or not | C ++ implementation to check whether all the bits are unset in the given range or not ; 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 will only have one or more set bits in the range l to r and nowhere else ; if new num is 0 , then all bits are unset in the given range ; else all bits are not unset ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; string allBitsSetInTheGivenRange ( unsigned int n , unsigned int l , unsigned int r ) { int num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; int new_num = n & num ; if ( new_num == 0 ) return " Yes " ; return " No " ; } int main ( ) { unsigned int n = 17 ; unsigned int l = 2 , r = 4 ; cout << allBitsSetInTheGivenRange ( n , l , r ) ; return 0 ; }
Toggle all bits after most significant bit | CPP program to toggle set bits starting from MSB ; Returns a number which has all set bits starting from MSB of n ; This makes sure two bits ( From MSB and including MSB ) are set ; This makes sure 4 bits ( From MSB and including MSB ) are set ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int setAllBitsAfterMSB ( int n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return n ; } void toggle ( int & n ) { n = n ^ setAllBitsAfterMSB ( n ) ; } int main ( ) { int n = 10 ; toggle ( n ) ; cout << n ; return 0 ; }
Check if a number has two adjacent set bits | CPP program to check if there are two adjacent set bits . ; Driver Code
#include <iostream> NEW_LINE using namespace std ; bool adjacentSet ( int n ) { return ( n & ( n >> 1 ) ) ; } int main ( ) { int n = 3 ; adjacentSet ( n ) ? cout << " Yes " : cout << " No " ; return 0 ; }
Position of rightmost common bit in two numbers | C ++ implementation to find the position of rightmost same bit ; Function to find the position of rightmost set bit in ' n ' ; Function to find the position of rightmost same bit in the binary representations of ' m ' and ' n ' ; position of rightmost same bit ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getRightMostSetBit ( unsigned int n ) { return log2 ( n & - n ) + 1 ; } int posOfRightMostSameBit ( unsigned int m , unsigned int n ) { return getRightMostSetBit ( ~ ( m ^ n ) ) ; } int main ( ) { int m = 16 , n = 7 ; cout << " Position ▁ = ▁ " << posOfRightMostSameBit ( m , n ) ; return 0 ; }