text
stringlengths
17
3.65k
code
stringlengths
60
5.26k
Sum of elements from an array having even parity | C # program to find the sum of the elements from an array which have even parity ; Function that returns true if x has even parity ; We basically count set bits https : www . geeksforgeeks . org / count - set - bits - in - an - integer / ; Function to return the sum of the elements from an array which have even parity ; If a [ i ] has even parity ; Driver code
using System ; class GFG { static bool checkEvenParity ( int x ) { int parity = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; parity ++ ; } if ( parity % 2 == 0 ) return true ; else return false ; } static long sumlist ( int [ ] a , int n ) { long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( checkEvenParity ( a [ i ] ) ) sum += a [ i ] ; } return sum ; } public static void Main ( ) { int [ ] arr = { 2 , 4 , 3 , 5 , 9 } ; int n = arr . Length ; Console . WriteLine ( sumlist ( arr , n ) ) ; } }
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
using System ; public class GFG { static 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 ; } static public void Main ( ) { int [ ] A = { 5 , 6 , 2 , 8 } ; int N = A . Length ; Console . WriteLine ( findOddPair ( A , N ) ) ; } }
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
using System ; class GFG { static 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 ; } public static void Main ( ) { int [ ] A = { 5 , 4 , 7 , 2 , 1 } ; int N = A . Length ; Console . WriteLine ( findevenPair ( A , N ) ) ; } }
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
using System ; public class GFG { static 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 ; } public static void Main ( ) { int [ ] a = { 5 , 4 , 7 , 2 , 1 } ; int n = a . Length ; Console . Write ( findEvenPair ( a , n ) ) ; } }
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
using System ; class GFG { static 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 ; } public static void Main ( ) { int [ ] a = { 5 , 1 , 3 , 2 } ; int n = a . Length ; Console . WriteLine ( findevenPair ( a , n ) ) ; } }
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
using System ; public class GFG { static 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 ; } static public void Main ( ) { int [ ] a = { 5 , 1 , 3 , 2 } ; int n = a . Length ; Console . WriteLine ( findevenPair ( a , n ) ) ; } }
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
using System ; class GFG { static int calculate ( int X ) { int number_of_bits = 8 ; return ( ( 1 << number_of_bits ) - 1 ) ^ X ; } public static void Main ( ) { int X = 4 ; Console . WriteLine ( " Required ▁ Number ▁ is ▁ : ▁ " + calculate ( X ) ) ; } }
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
using System ; using System . Collections ; using System . Linq ; class GFG { static int xorGivenSetBits ( int [ ] arr , int n , int k ) { ArrayList v = new ArrayList ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( Convert . ToString ( arr [ i ] , 2 ) . Count ( c => c == '1' ) == k ) { v . Add ( arr [ i ] ) ; } } int result = ( int ) v [ 0 ] ; for ( int i = 1 ; i < v . Count ; i ++ ) result = result ^ ( int ) v [ i ] ; return result ; } static void Main ( ) { int [ ] arr = { 2 , 13 , 1 , 19 , 7 } ; int n = arr . Length ; int k = 3 ; Console . WriteLine ( xorGivenSetBits ( arr , n , k ) ) ; } }
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 .
using System ; public class GFG { static 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 ] ; } } static public void Main ( ) { int [ ] arr = { 2 , 3 , 3 , 5 , 5 } ; int n = arr . Length ; ReplaceElements ( arr , n ) ; for ( int i = 0 ; i < n ; ++ i ) { Console . Write ( arr [ i ] + " ▁ " ) ; } } }
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
using System ; public class GFG { static int countLeadingZeros ( int x ) { int 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 ; } static int FindStringof1s ( int 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 ; } static public void Main ( ) { int x = 35 ; int n = 2 ; Console . WriteLine ( FindStringof1s ( x , n ) ) ; } }
Assign other value to a variable from two possible values | C # program to change value of x according to its current value . ; Function to alternate the values ; Main function
using System ; public class GFG { static int alternate ( int a , int b , int x ) { return x = a ^ b ^ x ; } public static void Main ( ) { int a = - 10 ; int b = 15 ; int x = a ; Console . Write ( " x ▁ is ▁ : ▁ " + x ) ; x = alternate ( a , b , x ) ; Console . Write ( " STRNEWLINE After ▁ exchange ▁ " ) ; Console . Write ( " x is : " } }
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. ; Driver Code
using System ; class GFG { static byte sizeofInt = 8 ; static int countZeros ( int x ) { int total_bits = sizeofInt * 8 ; int res = 0 ; while ( ( x & ( 1 << ( total_bits - 1 ) ) ) == 0 ) { x = ( x << 1 ) ; res ++ ; } return res ; } public static void Main ( String [ ] args ) { int x = 101 ; Console . WriteLine ( countZeros ( x ) ) ; } }
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 ; Driver Code
using System ; class GFG { static int countZeros ( int x ) { int 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 ; } static public void Main ( ) { int x = 101 ; Console . WriteLine ( countZeros ( x ) ) ; } }
Comparing leading zeros in binary representations of two numbers | C # 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 ; Driver Code
using System ; class GFG { static void LeadingZeros ( int x , int y ) { if ( ( x ^ y ) <= ( x & y ) ) Console . WriteLine ( " STRNEWLINE Equal " ) ; else if ( ( x & ( ~ y ) ) > y ) Console . WriteLine ( y ) ; else Console . WriteLine ( x ) ; } static public void Main ( ) { int x = 10 , y = 16 ; LeadingZeros ( x , y ) ; } }
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 codeM
using System ; class GfG { static void printSubSets ( int numOfBits , int num ) { if ( num >= 0 ) { Console . Write ( " { ▁ " ) ; subset ( numOfBits - 1 , num , numOfBits ) ; Console . WriteLine ( " } " ) ; printSubSets ( numOfBits , num - 1 ) ; } else return ; } static void subset ( int nthBit , int num , int numOfBits ) { if ( nthBit >= 0 ) { if ( ( num & ( 1 << nthBit ) ) != 0 ) { Console . Write ( numOfBits - nthBit + " ▁ " ) ; } subset ( nthBit - 1 , num , numOfBits ) ; } else return ; } public static void Main ( String [ ] args ) { int n = 4 ; printSubSets ( n , ( int ) ( Math . 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
using System ; class GFG { static void solve ( int A , int B ) { int count = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { if ( ( ( A >> i ) & 1 ) != ( ( B >> i ) & 1 ) ) { count ++ ; } } Console . WriteLine ( " Number ▁ of ▁ different ▁ bits ▁ : ▁ " + count ) ; } public static void Main ( ) { int A = 12 , B = 15 ; solve ( A , B ) ; } }
Set the rightmost off bit | C # program to set the rightmost unset bit ; If all bits are set ; Set rightmost 0 bit ; Driver program to test above
using System ; public class GFG { static int setRightmostUnsetBit ( int n ) { if ( ( n & ( n + 1 ) ) == 0 ) return n ; return n | ( n + 1 ) ; } public static void Main ( ) { int n = 21 ; Console . WriteLine ( setRightmostUnsetBit ( n ) ) ; } }
Print the number of set bits in each node of a Binary Tree | C # 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
using System ; class GFG { public class Node { public int data ; public Node left , right ; } ; static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = node . right = null ; return ( node ) ; } static void printSetBit ( Node root ) { if ( root == null ) return ; Console . Write ( " Set ▁ bits ▁ in ▁ Node ▁ " + root . data + " ▁ = ▁ " + bitCount ( root . data ) + " STRNEWLINE " ) ; printSetBit ( root . left ) ; printSetBit ( root . right ) ; } static int bitCount ( int x ) { int setBits = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; setBits ++ ; } return setBits ; } public static void Main ( String [ ] args ) { 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 ) ; } }
Find bitwise AND ( & ) of all possible sub | C # program to find of all the sub - arrays ; function to return AND of sub - arrays ; Driver code ; size of the array ; print and of all subarrays
using System ; public class GFG { static int AND ( int [ ] a , int n ) { int ans = a [ 0 ] ; for ( int i = 0 ; i < n ; ++ i ) ans &= a [ i ] ; return ans ; } public static void Main ( ) { int [ ] a = { 1 , 2 , 3 } ; int n = a . Length ; Console . WriteLine ( AND ( a , n ) ) ; } }
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
using System ; class GFG { static void TwoscomplementbyXOR ( string str ) { int n = str . Length ; bool check_bit = false ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == '0' && check_bit == false ) { continue ; } else { if ( check_bit == true ) { if ( str [ i ] == '0' ) str = str . Substring ( 0 , i ) + '1' + str . Substring ( i + 1 ) ; else str = str . Substring ( 0 , i ) + '0' + str . Substring ( i + 1 ) ; } check_bit = true ; } } if ( check_bit == false ) { Console . WriteLine ( "1" + str ) ; } else Console . WriteLine ( str ) ; } static void Main ( ) { string str = "101" ; TwoscomplementbyXOR ( str ) ; } }
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 code
using System ; class GFG { static bool isKthBitSet ( int n , int k ) { if ( ( n >> ( k - 1 ) ) == 1 ) return true ; return false ; } static int setKthBit ( int n , int k ) { return ( ( 1 << ( k - 1 ) ) n ) ; } static bool allBitsAreSet ( int n ) { if ( ( ( n + 1 ) & n ) == 0 ) return true ; return false ; } static bool bitsAreInAltOrder ( int n ) { int num = n ^ ( n >> 1 ) ; return allBitsAreSet ( num ) ; } static bool bitsAreInAltPatrnInGivenRange ( int n , int l , int r ) { 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 ) ; } public static void Main ( ) { int n = 18 ; int l = 1 , r = 3 ; if ( bitsAreInAltPatrnInGivenRange ( n , l , r ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
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 Code
using System ; class GFG { static bool bitsAreInAltPatrnInGivenTRange ( int n , int l , int r ) { 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 ; } static void Main ( ) { int n = 18 ; int l = 1 , r = 3 ; if ( bitsAreInAltPatrnInGivenTRange ( n , l , r ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Increment a number without using ++ or + | C # program to increment an unsigned int using bitwise operators . ; function that increment the value . ; Invert bits and apply negative sign ; Driver code
using System ; class GFG { static long increment ( long i ) { i = - ( ~ i ) ; return i ; } public static void Main ( ) { long n = 3 ; Console . WriteLine ( increment ( n ) ) ; } }
First element greater than or equal to X in prefix sum of N numbers using Binary Lifting | C # 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
using System ; class GFG { static 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 ] ; } static int BinaryLifting ( int [ ] presum , int n , int x ) { int pos = 0 ; int LOGN = ( int ) Math . Log ( 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 ; } public static void Main ( ) { int [ ] arr = { 2 , 5 , 7 , 1 , 6 , 9 , 12 , 4 , 6 } ; int x = 8 ; int n = arr . Length ; int [ ] presum = new int [ n ] ; MakePreSum ( arr , presum , n ) ; Console . WriteLine ( BinaryLifting ( presum , n , x ) ) ; } }
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
using System ; class GFG { static int bit_count ( int n ) { int count = 0 ; while ( n > 0 ) { count ++ ; n = n & ( n - 1 ) ; } return count ; } static int maxsum ( int [ ] arr , int n ) { int [ ] bits = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { bits [ i ] = bit_count ( arr [ i ] ) ; } int [ ] sum = new int [ 32 ] ; for ( int i = 0 ; i < n ; i ++ ) { sum [ bits [ i ] ] += arr [ i ] ; } int maximum = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { maximum = Math . Max ( sum [ i ] , maximum ) ; } return maximum ; } static void Main ( ) { int [ ] arr = { 2 , 3 , 8 , 5 , 6 , 7 } ; int n = arr . Length ; Console . WriteLine ( maxsum ( arr , n ) ) ; } }
Sum of XOR of sum of all pairs in an array | C # program to find XOR of pair sums . ; Driver code
using System ; class GFG { static int xorPairSum ( int [ ] ar , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum = sum ^ ar [ i ] ; return 2 * sum ; } static public void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 } ; int n = arr . Length ; Console . WriteLine ( xorPairSum ( arr , n ) ) ; } }
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 Code
using System ; class GFG { static int findEvenPair ( int [ ] A , int N ) { int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) if ( ( ! ( ( A [ i ] & 1 ) > 0 ) ) ) count ++ ; return count * ( count - 1 ) / 2 ; } public static void Main ( String [ ] args ) { int [ ] A = { 5 , 6 , 2 , 8 } ; int N = A . Length ; Console . WriteLine ( findEvenPair ( A , N ) ) ; } }
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 Code
using System ; class GFG { static bool allBitsSetInTheGivenRange ( int n , int l , int r ) { int num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; int new_num = n & num ; if ( new_num == 0 ) return true ; return false ; } public static void Main ( ) { int n = 17 ; int l = 2 , r = 4 ; if ( allBitsSetInTheGivenRange ( n , l , r ) ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }
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
using System ; public class GFG { static bool checkSame ( int n ) { int set = 0 ; int unset = 0 ; while ( n > 0 ) { if ( ( n & 1 ) == 1 ) set ++ ; else unset ++ ; n = n >> 1 ; } if ( set == unset ) return true ; else return false ; } static public void Main ( ) { int n = 12 ; if ( checkSame ( n ) ) Console . WriteLine ( " YES " ) ; else Console . WriteLine ( " NO " ) ; } }
Check if concatenation of two strings is balanced or not | C # 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 .
using System ; using System . Collections . Generic ; class GFG { static bool isBalanced ( String s ) { Stack < char > st = new Stack < char > ( ) ; int n = s . Length ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' ( ' ) { st . Push ( s [ i ] ) ; } else if ( st . Count == 0 ) { return false ; } else { st . Pop ( ) ; } } if ( st . Count != 0 ) { return false ; } return true ; } static bool isBalancedSeq ( String s1 , String s2 ) { if ( isBalanced ( s1 + s2 ) ) { return true ; } return isBalanced ( s2 + s1 ) ; } public static void Main ( String [ ] args ) { String s1 = " ) ( ) ( ( ) ) ) ) " ; String s2 = " ( ( ) ( ( ) ( " ; if ( isBalancedSeq ( s1 , s2 ) ) { Console . WriteLine ( " Balanced " ) ; } else { Console . WriteLine ( " Not ▁ Balanced " ) ; } } }
Find iΓ’ €ℒ th index character in a binary string obtained after n iterations | Set 2 | C # program to find ith 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
using System ; class GFG { static void KthCharacter ( int m , int n , int k ) { int distance = ( int ) Math . Pow ( 2 , n ) ; int Block_number = k / distance ; int remaining = k % distance ; int [ ] s = new int [ 32 ] ; int x = 0 ; for ( ; m > 0 ; x ++ ) { s [ x ] = m % 2 ; m = m / 2 ; } int root = s [ x - 1 - Block_number ] ; if ( remaining == 0 ) { Console . WriteLine ( root ) ; return ; } Boolean flip = true ; while ( remaining > 1 ) { if ( ( remaining & 1 ) > 0 ) { flip = ! flip ; } remaining = remaining >> 1 ; } if ( flip ) { Console . WriteLine ( ! ( root > 0 ) ) ; } else { Console . WriteLine ( root ) ; } } public static void Main ( ) { int m = 5 , k = 5 , n = 3 ; KthCharacter ( m , n , k ) ; } }
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 Code
using System ; class GFG { static bool onlyFirstAndLastAreSet ( int n ) { if ( n == 1 ) return true ; if ( n == 2 ) return false ; return ( ( ( n - 1 ) & ( n - 2 ) ) == 0 ) ; } public static void Main ( ) { int n = 9 ; if ( onlyFirstAndLastAreSet ( n ) ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }
Number with set bits only between L | C # 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
using System ; class GFG { static int getInteger ( int L , int R ) { int number = 0 ; for ( int i = L ; i <= R ; i ++ ) number += ( int ) Math . Pow ( 2 , i ) ; return number ; } public static void Main ( ) { int L = 2 , R = 5 ; Console . Write ( getInteger ( L , R ) ) ; } }
Number with set bits only between L | C # 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
using System ; class GFG { static int setbitsfromLtoR ( int L , int R ) { return ( 1 << ( R + 1 ) ) - ( 1 << L ) ; } public static void Main ( ) { int L = 2 , R = 5 ; Console . WriteLine ( setbitsfromLtoR ( L , R ) ) ; } }
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
using System ; class GFG { static int findXor ( int [ ] arr , int n ) { int xoR = 0 ; for ( int i = 0 ; i < n ; i ++ ) { xoR = xoR ^ arr [ i ] ; } return xoR * 2 ; } public static void Main ( ) { int [ ] arr = { 1 , 5 , 6 } ; int n = arr . Length ; Console . WriteLine ( findXor ( arr , n ) ) ; } }
Largest set with bitwise OR equal to n | C # 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
using System ; using System . Collections . Generic ; class GFG { static void setBitwiseORk ( int n ) { List < int > v = new List < int > ( ) ; for ( int i = 0 ; i <= n ; i ++ ) { if ( ( i n ) == n ) { v . Add ( i ) ; } } for ( int i = 0 ; i < v . Count ; i ++ ) { Console . Write ( v [ i ] + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int n = 5 ; setBitwiseORk ( n ) ; } }
Two odd occurring elements in an array where all other occur even times | C # 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
using System ; class GFG { static 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 ) != 0 ) x = x ^ arr [ i ] ; else y = y ^ arr [ i ] ; } Console . WriteLine ( x + " ▁ " + y ) ; } public static void Main ( ) { int [ ] arr = { 2 , 3 , 3 , 4 , 4 , 5 } ; int n = arr . Length ; printOdds ( arr , n ) ; } }
Maximum subset with bitwise OR equal to k | C # 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 ; main function
using System ; using System . Collections ; class GFG { static void subsetBitwiseORk ( int [ ] arr , int n , int k ) { ArrayList v = new ArrayList ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] k ) == k ) { v . Add ( arr [ i ] ) ; } } int ans = 0 ; for ( int i = 0 ; i < v . Count ; i ++ ) ans = ans | ( int ) v [ i ] ; if ( ans != k ) { Console . WriteLine ( " Subset ▁ does " + " ▁ not ▁ exist " ) ; return ; } for ( int i = 0 ; i < v . Count ; i ++ ) Console . Write ( ( int ) v [ i ] + " ▁ " ) ; } static public void Main ( String [ ] args ) { int k = 3 ; int [ ] arr = { 1 , 4 , 2 } ; int n = arr . Length ; subsetBitwiseORk ( arr , n , k ) ; } }
Number whose XOR sum with given array is a given number k | C # 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 ; XOR of all elements in the array ; Driver Code to test above function
using System ; class GFG { static int findEletobeInserted ( int [ ] A , int n , int k ) { int ans = k ; for ( int i = 0 ; i < n ; i ++ ) ans ^= A [ i ] ; return ans ; } public static void Main ( ) { int [ ] A = { 1 , 2 , 3 , 4 , 5 } ; int n = A . Length ; int k = 10 ; Console . WriteLine ( findEletobeInserted ( A , n , k ) + " ▁ has ▁ to ▁ be ▁ inserted ▁ in ▁ " + " the ▁ given ▁ array ▁ to ▁ make " + " ▁ xor ▁ sum ▁ of ▁ " + k ) ; } }
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
using System ; class GFG { static int [ ] BitCount = new int [ 10000 ] ; static 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 ] ; } static void Query ( int [ , ] Q , int q ) { for ( int i = 0 ; i < q ; i ++ ) Console . WriteLine ( ( BitCount [ Q [ i , 1 ] ] - BitCount [ Q [ i , 0 ] - 1 ] ) ) ; } public static void Main ( ) { int [ ] Arr = { 1 , 5 , 6 , 10 , 9 , 4 , 67 } ; int n = Arr . Length ; fillSetBitsMatrix ( Arr , n ) ; int q = 2 ; int [ , ] Q = { { 1 , 5 } , { 2 , 6 } } ; Query ( Q , q ) ; } }
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 ; Driver code
using System ; class GFG { static 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 ++ ) Console . Write ( '0' ) ; for ( int j = i - 1 ; j >= 0 ; j -- ) Console . Write ( binaryNumber [ j ] ) ; } static void generateGrayarr ( int n ) { int N = 1 << n ; for ( int i = 0 ; i < N ; i ++ ) { int x = i ^ ( i >> 1 ) ; decimalToBinaryNumber ( x , n ) ; Console . WriteLine ( ) ; } } public static void Main ( ) { int n = 3 ; generateGrayarr ( n ) ; } }
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
using System ; class GFG { static int BITS = 32 ; static 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 ) ) != 0 ) countSetBits ++ ; } int subset = ( 1 << countSetBits ) - 1 ; subset = ( subset * ( 1 << i ) ) ; ans += subset ; } return ans ; } static public void Main ( ) { int [ ] arr = { 1 , 2 , 3 } ; int size = 3 ; Console . WriteLine ( andSum ( arr , size ) ) ; } }
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 along 32 bits are set . ; find a number witn n least significant set bits . ; Now shift result by 32 - n ; Driver Code
using System ; class GFG { static long _popcnt32 ( long n ) { long count = 0 ; while ( n != 0 ) { n = n & ( n - 1 ) ; count ++ ; } return count ; } static long maximize ( long a ) { long n = _popcnt32 ( a ) ; if ( n == 32 ) return a ; long res = ( 1 << Convert . ToInt32 ( n ) ) - 1 ; return ( res << ( 32 - Convert . ToInt32 ( n ) ) ) ; } static void Main ( ) { long a = 3 ; Console . WriteLine ( maximize ( a ) ) ; } }
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 Code .
using System ; using System . Linq ; using System . Collections . Generic ; class GFG { static long minimize ( long a ) { string binaryString = Convert . ToString ( a , 2 ) ; int n = binaryString . Split ( new [ ] { '0' } , StringSplitOptions . RemoveEmptyEntries ) . Length + 1 ; return ( ( long ) Math . Pow ( 2 , n ) - 1 ) ; } static void Main ( ) { long a = 11 ; Console . Write ( minimize ( a ) ) ; } }
Maximum steps to transform 0 to X with bitwise AND | C # code to find the maximum possible effort ; Function to get no . of set bits in binary representation of positive integer n ; Driver code
using System ; class GFG { static int countSetBits ( int n ) { int count = 0 ; while ( n != 0 ) { count += n & 1 ; n >>= 1 ; } return count ; } public static void Main ( String [ ] args ) { int i = 3 ; Console . Write ( countSetBits ( i ) ) ; } }
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
using System ; public class GFG { static bool isEven ( int n ) { bool isEven = true ; for ( int i = 1 ; i <= n ; i ++ ) isEven = ! isEven ; return isEven ; } public static void Main ( ) { int n = 101 ; if ( isEven ( n ) ) Console . Write ( " Even " ) ; else Console . Write ( " Odd " ) ; } }
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
using System ; class GFG { static bool isEven ( int n ) { return ( ( n / 2 ) * 2 == n ) ; } public static void Main ( String [ ] args ) { int n = 101 ; if ( isEven ( n ) != false ) Console . Write ( " Even " ) ; else Console . Write ( " Odd " ) ; } }
Bitwise recursive addition of two integers | C # 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
using System ; class GFG { static int add ( int x , int y ) { int keep = ( x & y ) << 1 ; int res = x ^ y ; if ( keep == 0 ) return res ; return add ( keep , res ) ; } public static void Main ( ) { Console . Write ( add ( 15 , 38 ) ) ; } }
Count pairs in an array which have at least one digit common | C # 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
using System ; class GFG { static bool checkValidPair ( int num1 , int num2 ) { string s1 = num1 . ToString ( ) ; string s2 = num2 . ToString ( ) ; for ( int i = 0 ; i < s1 . Length ; i ++ ) for ( int j = 0 ; j < s2 . Length ; j ++ ) if ( s1 [ i ] == s2 [ j ] ) return true ; return false ; } static 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 ; } static void Main ( ) { int [ ] arr = new int [ ] { 10 , 12 , 24 } ; int n = arr . Length ; Console . WriteLine ( countPairs ( arr , n ) ) ; } }
Check if bitwise AND of any subset is power of two | C # 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 Code
using System ; using System . Collections . Generic ; class GFG { static int NUM_BITS = 32 ; static bool isPowerOf2 ( int num ) { if ( num != 0 && ( num & ( num - 1 ) ) == 0 ) return true ; return false ; } static 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 ++ ) { int p = arr [ j ] & ( 1 << i ) ; if ( p == 0 ) ans = ans & arr [ j ] ; } if ( isPowerOf2 ( ans ) ) return true ; } return false ; } public static void Main ( ) { int [ ] arr = { 12 , 13 , 7 } ; int n = arr . Length ; if ( checkSubsequence ( arr , n ) ) Console . Write ( " YES STRNEWLINE " ) ; else Console . Write ( " NO STRNEWLINE " ) ; } }
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
using System ; class GFG { static int getMid ( int s , int e ) { return s + ( e - s ) / 2 ; } static void constructSTUtil ( int [ ] arr , int ss , int se , int [ ] st , int si , bool 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 ) { st [ si ] = ( st [ 2 * si + 1 ] st [ 2 * si + 2 ] ) ; } else { st [ si ] = ( st [ 2 * si + 1 ] ^ st [ 2 * si + 2 ] ) ; } } static int [ ] constructST ( int [ ] arr , int n ) { int x = ( int ) ( Math . Ceiling ( Math . Log ( n ) / Math . Log ( 2 ) ) ) ; int max_size = 2 * ( int ) Math . Pow ( 2 , x ) - 1 ; int [ ] st = new int [ max_size ] ; bool operationAtRoot = ! ( x % 2 == 0 ) ; constructSTUtil ( arr , 0 , n - 1 , st , 0 , operationAtRoot ) ; return st ; } static public void Main ( ) { int [ ] leaves = { 1 , 6 , 3 , 7 , 5 , 9 , 10 , 4 } ; int n = leaves . Length ; int [ ] segmentTree = constructST ( leaves , n ) ; int rootIndex = 0 ; Console . WriteLine ( " Value ▁ at ▁ Root ▁ Node ▁ = ▁ " + segmentTree [ rootIndex ] ) ; } }
Leftover element after performing alternate Bitwise OR and Bitwise XOR operations on adjacent pairs | C # 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
using System ; using System . Collections . Generic ; class GFG { static int N = 1000 ; static int lastElement ( int [ ] a , int n ) { int steps = 1 ; List < int > [ ] v = new List < int > [ N ] ; for ( int i = 0 ; i < N ; i ++ ) v [ i ] = new List < int > ( ) ; if ( n == 1 ) return a [ 0 ] ; for ( int i = 0 ; i < n ; i += 2 ) v [ steps ] . Add ( a [ i ] a [ i + 1 ] ) ; while ( v [ steps ] . Count > 1 ) { steps += 1 ; for ( int i = 0 ; i < v [ steps - 1 ] . Count ; i += 2 ) { if ( steps % 2 == 1 ) v [ steps ] . Add ( v [ steps - 1 ] [ i ] v [ steps - 1 ] [ i + 1 ] ) ; v [ steps ] . Add ( v [ steps - 1 ] [ i ] ^ v [ steps - 1 ] [ i + 1 ] ) ; } } return v [ steps ] [ 0 ] ; } public static void Main ( String [ ] args ) { int [ ] a = { 1 , 4 , 5 , 6 } ; int n = a . Length ; int index = 0 ; int value = 2 ; a [ 0 ] = 2 ; Console . WriteLine ( lastElement ( a , n ) ) ; index = 3 ; value = 5 ; a [ index ] = value ; Console . WriteLine ( lastElement ( a , n ) ) ; } }
Find the winner in nim | C # to find nim - game winner ; function to find winner of NIM - game ; case when Alice is winner ; when Bob is winner ; Driver code
using System ; class GFG { static 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 " ; } public static void Main ( ) { int [ ] A = { 1 , 4 , 3 , 5 } ; int n = A . Length ; Console . WriteLine ( " Winner ▁ = ▁ " + findWinner ( A , n ) ) ; } }
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
using System ; class GFG { static bool isFibbinaryNum ( int n ) { if ( ( n & ( n >> 1 ) ) == 0 ) return true ; return false ; } public static void Main ( ) { int n = 10 ; if ( isFibbinaryNum ( n ) == true ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Maximum XOR | Program to obtain maximum XOR value sub - array ; function to calculate maximum XOR value ; Return ( 2 ^ c - 1 ) ; Driver Code
using System ; class GFG { static int maxXOR ( int n , int k ) { int c = ( int ) ( Math . Log ( n ) / Math . Log ( 2 ) ) + 1 ; return ( ( 1 << c ) - 1 ) ; } public static void Main ( String [ ] args ) { int n = 12 ; int k = 3 ; Console . Write ( maxXOR ( n , k ) ) ; } }
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
using System ; class GFG { public static long divide ( long dividend , long divisor ) { long sign = ( ( dividend < 0 ) ^ ( divisor < 0 ) ) ? - 1 : 1 ; dividend = Math . Abs ( dividend ) ; divisor = Math . Abs ( divisor ) ; long quotient = 0 , temp = 0 ; for ( int i = 31 ; i >= 0 ; -- i ) { if ( temp + ( divisor << i ) <= dividend ) { temp += divisor << i ; quotient |= 1L L << i ; } } if ( sign == - 1 ) quotient = - quotient ; return quotient ; } public static void Main ( ) { int a = 10 , b = 3 ; Console . WriteLine ( divide ( a , b ) ) ; int a1 = 43 , b1 = - 8 ; Console . WriteLine ( divide ( a1 , b1 ) ) ; } }
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
using System ; class GFG { static int count ( int n ) { int c = 0 ; while ( n != 0 ) { c ++ ; n = n >> 1 ; } return c ; } static int XOR ( int a , int b ) { int c = Math . Min ( a , b ) ; int d = Math . Max ( a , b ) ; if ( count ( c ) < count ( d ) ) c = c << ( count ( d ) - count ( c ) ) ; return ( c ^ d ) ; } public static void Main ( ) { int a = 13 , b = 5 ; Console . WriteLine ( XOR ( a , b ) ) ; } }
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
using System ; public class GFG { static 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 ( Math . Abs ( oddbits - evenbits ) % 3 == 0 ) { Console . Write ( " Yes " + " STRNEWLINE " ) ; } else { Console . Write ( " No " + " STRNEWLINE " ) ; } } public static void Main ( String [ ] args ) { String A = "10101" ; CheckDivisibilty ( A ) ; } }
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
using System ; public class GFG { static uint swapBitsInPair ( uint x ) { return ( ( x & 010101010 ) >> 1 ) | ( ( x & 001010101 ) << 1 ) ; } static public void Main ( ) { uint x = 4 ; Console . WriteLine ( swapBitsInPair ( x ) ) ; } }
Alternate bits of two numbers to create a new number | C # 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
using System ; class GFG { static 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 ) ; } static 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 ) ; } static int getAlternateBits ( int n , int m ) { int tempn = setevenbits ( n ) ; int tempm = setoddbits ( m ) ; return ( tempn tempm ) ; } public static void Main ( ) { int n = 10 ; int m = 11 ; Console . WriteLine ( getAlternateBits ( n , m ) ) ; } }
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
using System ; class GFG { static bool isDivisibleBy10 ( string 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 ; } static bool isDivisibleBy20 ( string bin , int n ) { if ( bin [ n - 1 ] == '1' ) return false ; return isDivisibleBy10 ( bin , n - 1 ) ; } public static void Main ( ) { string bin = "101000" ; int n = bin . Length ; if ( isDivisibleBy20 ( bin , n - 1 ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
For every set bit of a number toggle bits of other | C # program toggle bits of n2 that are at same position as set bits of n1 . ; function for the Nega_bit ; Driver program
using System ; class GFG { static int toggleBits ( int n1 , int n2 ) { return ( n1 ^ n2 ) ; } public static void Main ( ) { int n1 = 2 , n2 = 5 ; Console . WriteLine ( toggleBits ( n1 , n2 ) ) ; } }
Toggle all even bits of a number | C # 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
using System ; class GFG { static 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 ; } public static void Main ( ) { int n = 11 ; Console . WriteLine ( evenbittogglenumber ( n ) ) ; } }
Toggle first and last bits of a number | C # 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
using System ; class GFG { static int takeLandFsetbits ( int n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return ( ( n + 1 ) >> 1 ) + 1 ; } static int toggleFandLbits ( int n ) { if ( n == 1 ) return 0 ; return n ^ takeLandFsetbits ( n ) ; } public static void Main ( ) { int n = 10 ; Console . WriteLine ( toggleFandLbits ( n ) ) ; } }
Odious number | 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
using System ; class GFG { static int countSetBits ( int n ) { int count = 0 ; while ( n != 0 ) { n &= ( n - 1 ) ; count ++ ; } return count ; } static bool checkOdious ( int n ) { return ( countSetBits ( n ) % 2 == 1 ) ; } public static void Main ( ) { int num = 32 ; if ( checkOdious ( num ) ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }
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
using System ; class GFG { static 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 ) ) ) ; } public static void Main ( ) { int n = 10 ; Console . WriteLine ( setleftmostunsetbit ( n ) ) ; } }
Maximum XOR using K numbers from 1 to n | C # 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
using System ; public class main { static int maxXorSum ( int n , int k ) { if ( k == 1 ) return n ; int res = 1 ; while ( res <= n ) res <<= 1 ; return res - 1 ; } public static void Main ( ) { int n = 4 , k = 3 ; Console . WriteLine ( maxXorSum ( n , k ) ) ; } }
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
using System ; class GFG { static int getPosOfRightmostSetBit ( int n ) { return ( int ) ( Math . Log ( n & - n ) / Math . Log ( 2 ) ) ; } static int toggleLastKBits ( int n , int k ) { int num = ( 1 << k ) - 1 ; return ( n ^ num ) ; } static int incrementByOne ( int n ) { int k = getPosOfRightmostSetBit ( ~ n ) ; n = ( ( 1 << k ) n ) ; if ( k != 0 ) n = toggleLastKBits ( n , k ) ; return n ; } public static void Main ( ) { int n = 15 ; Console . WriteLine ( incrementByOne ( n ) ) ; } }
XNOR of two numbers | C # program to find XNOR of two numbers ; Make sure a is larger ; swapping a and b ; ; 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 function
using System ; public class GfG { public static int xnor ( int a , int b ) { if ( a < b ) { int t = a ; a = b ; b = t ; } if ( a == 0 && b == 0 ) return 1 ; int a_rem = 0 ; int b_rem = 0 ; int count = 0 ; int xnornum = 0 ; while ( true ) { a_rem = a & 1 ; b_rem = b & 1 ; if ( a_rem == b_rem ) xnornum |= ( 1 << count ) ; count ++ ; a = a >> 1 ; b = b >> 1 ; if ( a < 1 ) break ; } return xnornum ; } public static void Main ( ) { int a = 10 , b = 50 ; Console . WriteLine ( xnor ( a , b ) ) ; } }
XNOR of two numbers | C # 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 program
using System ; class GFG { static 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 ; } static int xnor ( int num1 , int num2 ) { if ( num1 < num2 ) { int temp = num1 ; num1 = num2 ; num2 = temp ; } num1 = togglebit ( num1 ) ; return num1 ^ num2 ; } public static void Main ( ) { int a = 10 , b = 20 ; Console . WriteLine ( xnor ( a , b ) ) ; } }
Maximum OR sum of sub | C # program to find maximum OR sum ; function to find maximum OR sum ; OR sum of all the elements in both arrays ; Driver code
using System ; class GFG { static 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 ] ; } Console . WriteLine ( sum1 + sum2 ) ; } public static void Main ( ) { int [ ] A = { 1 , 2 , 4 , 3 , 2 } ; int [ ] B = { 2 , 3 , 3 , 12 , 1 } ; int n = A . Length ; MaximumSum ( A , B , n ) ; } }
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 code
using System ; class GFG { static int posOfRightmostSetBit ( int n ) { return ( int ) ( Math . Log ( n & - n ) / Math . Log ( 2 ) ) + 1 ; } static int posOfCarryBit ( int a , int b ) { return posOfRightmostSetBit ( a & b ) ; } public static void Main ( ) { int a = 10 , b = 2 ; Console . Write ( posOfCarryBit ( a , b ) ) ; } }
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 code
using System ; class GFG { static bool isPowerOfTwo ( int x ) { return x != 0 && ( ( x & ( x - 1 ) ) == 0 ) ; } static bool differAtOneBitPos ( int a , int b ) { return isPowerOfTwo ( a ^ b ) ; } public static void Main ( ) { int a = 13 , b = 9 ; if ( differAtOneBitPos ( a , b ) == true ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Multiplication with a power of 2 | Simple C # program to compute x * ( 2 ^ n ) ; Returns 2 raised to power n ; Driver program
using System ; class GFG { static long power2 ( long n ) { if ( n == 0 ) return 1 ; if ( n == 1 ) return 2 ; return power2 ( n / 2 ) * power2 ( n / 2 ) ; } static long multiply ( long x , long n ) { return x * power2 ( n ) ; } public static void Main ( ) { long x = 70 , n = 2 ; Console . WriteLine ( multiply ( x , n ) ) ; } }
Multiplication with a power of 2 | C # Code for Multiplication with a power of 2 ; Driver program to test above function
using System ; class GFG { static int multiply ( int x , int n ) { return x << n ; } public static void Main ( ) { int x = 70 , n = 2 ; Console . WriteLine ( multiply ( x , n ) ) ; } }
Check if n is divisible by power of 2 without using arithmetic operators | C # Code for 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 function
using System ; class GFG { static bool isDivBy2PowerM ( int n , int m ) { if ( ( n & ( ( 1 << m ) - 1 ) ) == 0 ) return true ; return false ; } public static void Main ( ) { int n = 8 , m = 2 ; if ( isDivBy2PowerM ( n , m ) ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }
Game of Nim with removal of one stone allowed | C # Code 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 . ; Driver program to test above function
using System ; class GFG { static int findWinner ( int N ) { return N & 1 ; } public static void Main ( ) { int N = 15 ; if ( findWinner ( N ) == 1 ) Console . Write ( " Player ▁ A " ) ; else Console . Write ( " Player ▁ B " ) ; } }
Toggle all odd bits of a number | C # code for 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
using System ; class GFG { static 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 ; } public static void Main ( ) { int n = 11 ; Console . WriteLine ( evenbittogglenumber ( n ) ) ; } }
Quotient and remainder dividing by 2 ^ k ( a power of 2 ) | C # 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
using System ; public class GFG { static void divide ( int n , int m ) { Console . WriteLine ( " Remainder ▁ = ▁ " + ( ( n ) & ( m - 1 ) ) ) ; Console . WriteLine ( " Quotient ▁ = ▁ " + ( n >> ( int ) ( Math . Log ( m ) ) ) ) ; } static public void Main ( ) { int n = 43 , m = 8 ; divide ( n , m ) ; } }
Maximum AND value of a pair in an array | C # Program to find maximum XOR value of a pair ; Function for finding maximum and value pair ; Driver code
using System ; public class GfG { static 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 = res > ( arr [ i ] & arr [ j ] ) ? res : ( arr [ i ] & arr [ j ] ) ; return res ; } public static void Main ( ) { int [ ] arr = { 4 , 8 , 6 , 2 } ; int n = arr . Length ; Console . WriteLine ( " Maximum ▁ AND ▁ Value ▁ = ▁ " + maxAND ( arr , n ) ) ; } }
Check if a number is positive , negative or zero using bit operators | C # 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 code
using System ; class GFG { static int index ( int i ) { return 1 + ( i >> 31 ) - ( - i >> 31 ) ; } static void check ( int n ) { String [ ] s = { " negative " , " zero " , " positive " } ; int val = index ( n ) ; Console . WriteLine ( n + " ▁ is ▁ " + s [ val ] ) ; } public static void Main ( ) { check ( 30 ) ; check ( - 20 ) ; check ( 0 ) ; } }
Find two numbers from their sum and XOR | C # 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
using System ; public class GFG { static void compute ( long S , long X ) { long A = ( S - X ) / 2 ; int a = 0 , b = 0 ; for ( int i = 0 ; i < 8 * sizeof ( long ) ; i ++ ) { long Xi = ( X & ( 1 << i ) ) ; long 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 ) ; } { Console . WriteLine ( " Not ▁ Possible " ) ; return ; } } Console . WriteLine ( " a ▁ = ▁ " + a + " b = " } public static void ( ) { long S = 17 , X = 13 ; compute ( S , X ) ; } }
Divisibility by 64 with removal of bits allowed | C # 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
using System ; class GFG { static 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 && s [ i ] == '1' ) return true ; } return false ; } public static void Main ( ) { String s = "100010001" ; if ( checking ( s ) ) Console . WriteLine ( " Possible " ) ; else Console . WriteLine ( " Not ▁ possible " ) ; } }
Modify a bit at a given position | C # program to modify a bit at position p in n to b . ; Returns modified n . ; Driver Code
using System ; class GFG { public static int modifyBit ( int n , int p , int b ) { int mask = 1 << p ; return ( n & ~ mask ) | ( ( b << p ) & mask ) ; } static public void Main ( ) { Console . WriteLine ( modifyBit ( 6 , 2 , 0 ) ) ; Console . WriteLine ( modifyBit ( 6 , 5 , 1 ) ) ; } }
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 code
using System ; class GFG { static int countSetBits ( int n ) { int count = 0 ; while ( n > 0 ) { n &= ( n - 1 ) ; count ++ ; } return count ; } static int countSetBitsInGivenRange ( int n , int l , int r ) { int num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; return countSetBits ( n & num ) ; } public static void Main ( ) { int n = 42 ; int l = 2 , r = 5 ; Console . WriteLine ( countSetBitsInGivenRange ( n , l , r ) ) ; } }
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 function
using System ; class GFG { public static bool areAllBitsSet ( long n ) { if ( n == 0 ) return false ; if ( ( ( n + 1 ) & n ) == 0 ) return true ; return false ; } public static bool isOnesComplementOfOther ( long a , long b ) { return areAllBitsSet ( a ^ b ) ; } public static void Main ( ) { long a = 10 , b = 5 ; if ( isOnesComplementOfOther ( a , b ) ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }
Unique element in an array where all elements occur k times except one | C # 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
using System ; class GFG { static int findUnique ( int [ ] a , int n , int k ) { byte sizeof_int = 4 ; int INT_SIZE = 8 * sizeof_int ; int [ ] count = new int [ INT_SIZE ] ; for ( int i = 0 ; i < INT_SIZE ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( ( a [ j ] & ( 1 << i ) ) != 0 ) count [ i ] += 1 ; int res = 0 ; for ( int i = 0 ; i < INT_SIZE ; i ++ ) res += ( count [ i ] % k ) * ( 1 << i ) ; return res ; } public static void Main ( String [ ] args ) { int [ ] a = { 6 , 2 , 5 , 2 , 2 , 6 , 6 } ; int n = a . Length ; int k = 3 ; Console . WriteLine ( findUnique ( a , n , k ) ) ; } }
Check whether the number has only first and last bits set | C # program 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
using System ; class GFG { static bool powerOfTwo ( uint n ) { return ( ( n & n - 1 ) == 0 ) ; } static bool onlyFirstAndLastAreSet ( uint n ) { if ( n == 1 ) return true ; return powerOfTwo ( n - 1 ) ; } public static void Main ( ) { uint n = ( uint ) 9 ; if ( onlyFirstAndLastAreSet ( n ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
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 Code
using System ; class GFG { static bool allBitsAreSet ( int n ) { if ( ( ( n + 1 ) & n ) == 0 ) return true ; return false ; } static bool bitsAreInAltOrder ( int n ) { int num = n ^ ( n >> 1 ) ; return allBitsAreSet ( num ) ; } public static void Main ( ) { int n = 10 ; if ( bitsAreInAltOrder ( n ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Minimum flips required to maximize a number with k set bits | C # Code to find Minimum flips required to maximize a number with k set bits ; 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 Code
using System ; class GFG { static int setBit ( int xorValue ) { int count = 0 ; while ( xorValue >= 1 ) { if ( xorValue % 2 == 1 ) count ++ ; xorValue /= 2 ; } return count ; } static int minFlip ( int n , int k ) { int size = ( int ) ( Math . Log ( n ) / Math . Log ( 2 ) ) + 1 ; int max = ( int ) Math . Pow ( 2 , k ) - 1 ; max = max << ( size - k ) ; int xorValue = ( n ^ max ) ; return ( setBit ( xorValue ) ) ; } public static void Main ( ) { int n = 27 , k = 3 ; Console . Write ( " Min ▁ Flips ▁ = ▁ " + minFlip ( n , k ) ) ; } }
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
using System ; class GFG { static int setallbitgivenrange ( int n , int l , int r ) { int range = ( ( ( 1 << ( l - 1 ) ) - 1 ) ^ ( ( 1 << ( r ) ) - 1 ) ) ; return ( n range ) ; } static void Main ( ) { int n = 17 , l = 2 , r = 3 ; Console . Write ( setallbitgivenrange ( n , l , r ) ) ; } }
Count total bits in a number | C # program to find total bit in given number ; log function in base 2 take only integer part ; Driver code
using System ; class GFG { static uint countBits ( uint number ) { return ( uint ) Math . Log ( number , 2.0 ) + 1 ; } public static void Main ( ) { uint num = 65 ; Console . WriteLine ( countBits ( num ) ) ; } }
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 Code
using System ; public class GFG { static String allBitsSetInTheGivenRange ( int n , int l , int r ) { int num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; int new_num = n & num ; if ( new_num == 0 ) return " Yes " ; return " No " ; } static public void Main ( ) { int n = 17 ; int l = 2 ; int r = 4 ; Console . WriteLine ( allBitsSetInTheGivenRange ( n , l , r ) ) ; } }
Toggle all bits after most significant bit | C # 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
using System ; class GFG { static int setAllBitsAfterMSB ( int n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return n ; } static int toggle ( int n ) { n = n ^ setAllBitsAfterMSB ( n ) ; return n ; } public static void Main ( ) { int n = 10 ; n = toggle ( n ) ; Console . WriteLine ( n ) ; } }
Check if a number has two adjacent set bits | C # program to check if there are two adjacent set bits . ; Driver code
using System ; class GFG { static bool adjacentSet ( int n ) { int x = ( n & ( n >> 1 ) ) ; if ( x > 0 ) return true ; else return false ; } public static void Main ( ) { int n = 3 ; if ( adjacentSet ( n ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
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 code
using System ; class GFG { static int getRightMostSetBit ( int n ) { return ( int ) ( ( Math . Log ( n & - n ) ) / ( Math . Log ( 2 ) ) ) + 1 ; } static int posOfRightMostSameBit ( int m , int n ) { return getRightMostSetBit ( ~ ( m ^ n ) ) ; } public static void Main ( ) { int m = 16 , n = 7 ; Console . Write ( " Position ▁ = ▁ " + posOfRightMostSameBit ( m , n ) ) ; } }
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 same bit in the binary representations of ' m ' and ' n ' ; Initialize loop counter ; Check whether the value ' m ' is odd ; Check whether the value ' n ' is odd ; Below ' if ' checks for both values to be odd or even ; Right shift value of m ; Right shift value of n ; When no common set is found ; Driver code
using System ; class GFG { static int posOfRightMostSameBit ( int m , int n ) { int loopCounter = 1 ; while ( m > 0 n > 0 ) { Boolean a = m % 2 == 1 ; Boolean b = n % 2 == 1 ; if ( ! ( a ^ b ) ) { return loopCounter ; } m = m >> 1 ; n = n >> 1 ; loopCounter ++ ; } return - 1 ; } public static void Main ( String [ ] args ) { int m = 16 , n = 7 ; Console . Write ( " Position ▁ = ▁ " + posOfRightMostSameBit ( m , n ) ) ; } }
Check whether all the bits are set in the given range | C # implementation to check whether all the bits are set in the given range or not ; function to check whether all the bits are set 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 both are equal , then all bits are set in the given range ; else all bits are not set ; Driver code
using System ; class GFG { static String allBitsSetInTheGivenRange ( int n , int l , int r ) { int num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; int new_num = n & num ; if ( num == new_num ) return " Yes " ; return " No " ; } public static void Main ( ) { int n = 22 ; int l = 2 , r = 3 ; Console . Write ( allBitsSetInTheGivenRange ( n , l , r ) ) ; } }
1 to n bit numbers with no consecutive 1 s in binary representation | C # Code to Print all numbers upto n bits with no consecutive set bits . ; Let us first compute 2 raised to power n . ; loop 1 to n to check all the numbers ; A number i doesn ' t ▁ contain ▁ ▁ consecutive ▁ set ▁ bits ▁ if ▁ ▁ bitwise ▁ and ▁ of ▁ i ▁ and ▁ left ▁ ▁ shifted ▁ i ▁ do ' t contain a commons set bit . ; Driver code
using System ; class GFG { static void printNonConsecutive ( int n ) { int p = ( 1 << n ) ; for ( int i = 1 ; i < p ; i ++ ) if ( ( i & ( i << 1 ) ) == 0 ) Console . Write ( i + " ▁ " ) ; } public static void Main ( ) { int n = 3 ; printNonConsecutive ( n ) ; } }
Find the n | Efficient C # program to find n - th palindrome ; Construct the nth binary palindrome with the given group number , aux_number and operation type ; No need to insert any bit in the middle ; Length of the final binary representation ; Fill first and last bit as 1 ; Start filling the a [ ] from middle , with the aux_num binary representation ; Get the auxiliary number 's ith bit and fill around middle ; Insert bit 0 in the middle ; Length of the final binary representation ; Fill first and last bit as 1 ; Start filling the a [ ] from middle , with the aux_num binary representation ; Get the auxiliary number 's ith bit and fill around middle ; else Insert bit 1 in the middle ; Length of the final binary representation ; Fill first and last bit as 1 ; Start filling the a [ ] from middle , with the aux_num binary representation ; Get the auxiliary number 's ith bit and fill around middle ; Convert the number to decimal from binary ; Will return the nth binary palindrome number ; Add number of elements in all the groups , until the group of the nth number is found ; Total number of elements until this group ; Element 's offset position in the group ; Finding which bit to be placed in the middle and finding the number , which we will fill from the middle in both directions ; We need to fill this auxiliary number in binary form the middle in both directions ; op = 0 ; Need to Insert 0 at middle ; op = 1 ; Need to Insert 1 at middle ; Driver code ; Function Call
using System ; class GFG { static int INT_SIZE = 32 ; static int constructNthNumber ( int group_no , int aux_num , int op ) { int [ ] a = new int [ INT_SIZE ] ; int num = 0 , len_f ; int i = 0 ; if ( op == 2 ) { len_f = 2 * group_no ; a [ len_f - 1 ] = a [ 0 ] = 1 ; while ( aux_num > 0 ) { a [ group_no + i ] = a [ group_no - 1 - i ] = aux_num & 1 ; aux_num = aux_num >> 1 ; i ++ ; } } else if ( op == 0 ) { len_f = 2 * group_no + 1 ; a [ len_f - 1 ] = a [ 0 ] = 1 ; a [ group_no ] = 0 ; while ( aux_num > 0 ) { a [ group_no + 1 + i ] = a [ group_no - 1 - i ] = aux_num & 1 ; aux_num = aux_num >> 1 ; i ++ ; } } { len_f = 2 * group_no + 1 ; a [ len_f - 1 ] = a [ 0 ] = 1 ; a [ group_no ] = 1 ; while ( aux_num > 0 ) { a [ group_no + 1 + i ] = a [ group_no - 1 - i ] = aux_num & 1 ; aux_num = aux_num >> 1 ; i ++ ; } } for ( i = 0 ; i < len_f ; i ++ ) num += ( 1 << i ) * a [ i ] ; return num ; } static int getNthNumber ( int n ) { int group_no = 0 , group_offset ; int count_upto_group = 0 , count_temp = 1 ; int op , aux_num ; while ( count_temp < n ) { group_no ++ ; count_upto_group = count_temp ; count_temp += 3 * ( 1 << ( group_no - 1 ) ) ; } group_offset = n - count_upto_group - 1 ; if ( ( group_offset + 1 ) <= ( 1 << ( group_no - 1 ) ) ) { aux_num = group_offset ; } else { if ( ( ( group_offset + 1 ) - ( 1 << ( group_no - 1 ) ) ) % 2 == 1 ) else aux_num = ( ( group_offset ) - ( 1 << ( group_no - 1 ) ) ) / 2 ; } return constructNthNumber ( group_no , aux_num , op ) ; } public static void Main ( String [ ] args ) { int n = 9 ; Console . Write ( " { 0 } " , getNthNumber ( n ) ) ; } }