Open In App

Flip bits of the sum of count of set bits of two given numbers

Last Updated : 25 May, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two numbers A and B, the task is to count the number of set bits in A and B and flip the bits of the obtained sum.

Examples:

Input: A = 5, B = 7
Output: 2
Explanation:
Binary representation of A is 101.
Binary representation of B is 111.
Count of set bits in A and B = 2 + 3 = 5.
Binary representation of the sum obtained = 101
Flipping the bits of the sum, the number obtained is (010)2 = 2. 
Therefore, the required output is 2.

Input: A = 76, B = 35
Output: 1
Explanation: 
Binary representation of A is 1001100
Binary representation of B is 100011
Count of set bits in A and B = 3 + 3 = 6
Binary representation of the sum obtained = 110
Flipping the bits of the sum, the number obtained is (001)2 = 1. 
Therefore, the required output is 1.

 

Naive Approach: The idea to solve this problem is to first traverse through the binary representation of both the numbers and count number of set bits in both the numbers. Finally, add them and invert the bits of the resultant number.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count number of
// set bits in integer
int countSetBits(int n)
{
    // Variable for counting set bits
    int count = 0;
    while (n) {
        n &= (n - 1);
        count++;
    }
    return count;
}
 
// Function to invert bits of a number
int invertBits(int n)
{
    // Calculate number of bits of N-1;
    int x = log2(n);
 
    int m = 1 << x;
    m = m | m - 1;
    n = n ^ m;
 
    return n;
}
 
// Function to invert the sum
// of set bits in A and B
void invertSum(int A, int B)
{
 
    // Stores sum of set bits
    int temp = countSetBits(A)
               + countSetBits(B);
    cout << invertBits(temp) << endl;
}
 
// Driver Code
int main()
{
    int A = 5;
    int B = 7;
 
    invertSum(A, B);
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
   
class GFG{
  
// Function to count number of
// set bits in integer
static int countSetBits(int n)
{
     
    // Variable for counting set bits
    int count = 0;
     
    while (n != 0)
    {
        n &= (n - 1);
        count++;
    }
    return count;
}
  
// Function to invert bits of a number
static int invertBits(int n)
{
     
    // Calculate number of bits of N-1;
    int x = (int)(Math.log(n) / Math.log(2));
      
    int m = 1 << x;
    m = m | m - 1;
    n = n ^ m;
      
    return n;
}
  
// Function to invert the sum
// of set bits in A and B
static void invertSum(int A, int B)
{
     
    // Stores sum of set bits
    int temp = countSetBits(A) +
               countSetBits(B);
                 
    System.out.print(invertBits(temp));
}
   
// Driver Code
static public void main(String args[])
{
    int A = 5;
    int B = 7;
      
    invertSum(A, B);
}
}
 
// This code is contributed by susmitakundugoaldanga


Python3




# Python3 program for the above approach
import math
 
# Function to count number of
# set bits in integer
def countSetBits(n):
     
    # Variable for counting set bits
    count = 0
 
    while (n != 0):
        n &= (n - 1)
        count += 1
 
    return count
 
# Function to invert bits of a number
def invertBits(n):
     
    # Calculate number of bits of N-1;
    x = (int)(math.log(n) / math.log(2))
 
    m = 1 << x
    m = m | m - 1
    n = n ^ m
 
    return n
 
# Function to invert the sum
# of set bits in A and B
def invertSum(A, B):
     
    # Stores sum of set bits
    temp = countSetBits(A) + countSetBits(B)
 
    print(invertBits(temp))
 
# Driver Code
A = 5
B = 7
 
invertSum(A, B)
 
# This code is contributed by shikhasingrajput


C#




// C# program for the above approach
using System;
 
class GFG{
     
// Function to count number of
// set bits in integer
static int countSetBits(int n)
{
     
    // Variable for counting set bits
    int count = 0;
    while (n != 0)
    {
        n &= (n - 1);
        count++;
    }
    return count;
}
 
// Function to invert bits of a number
static int invertBits(int n)
{
     
    // Calculate number of bits of N-1;
    int x = (int)Math.Log(n, 2);
     
    int m = 1 << x;
    m = m | m - 1;
    n = n ^ m;
     
    return n;
}
 
// Function to invert the sum
// of set bits in A and B
static void invertSum(int A, int B)
{
     
    // Stores sum of set bits
    int temp = countSetBits(A) +
               countSetBits(B);
                
    Console.WriteLine(invertBits(temp));
}
 
// Driver Code
static void Main()
{
    int A = 5;
    int B = 7;
     
    invertSum(A, B);
}
}
 
// This code is contributed by divyesh072019


Javascript




<script>
 
// Javascript program for the above approach
 
// Function to count number of
// set bits in integer
function countSetBits(n)
{
     
    // Variable for counting set bits
    var count = 0;
     
    while (n != 0)
    {
        n &= (n - 1);
        count++;
    }
    return count;
}
  
// Function to invert bits of a number
function invertBits(n)
{
     
    // Calculate number of bits of N-1;
    var x = parseInt((Math.log(n) /
                      Math.log(2)));
      
    var m = 1 << x;
    m = m | m - 1;
    n = n ^ m;
      
    return n;
}
  
// Function to invert the sum
// of set bits in A and B
function invertSum(A, B)
{
     
    // Stores sum of set bits
    var temp = countSetBits(A) +
               countSetBits(B);
                 
    document.write(invertBits(temp));
}
   
// Driver Code
var A = 5;
var B = 7;
  
invertSum(A, B);
 
// This code is contributed by Rajput-Ji
 
</script>


Output: 

2

 

Time Complexity: O(logN)
Auxiliary Space: O(1)



Next Article

Similar Reads

Count of pairs {X, Y} from an array such that sum of count of set bits in X ⊕ Y and twice the count of set bits in X & Y is M
Given an array arr[] consisting of N non-negative integers and an integer M, the task is to find the count of unordered pairs {X, Y} of array elements that satisfies the condition setBits(X ⊕ Y) + 2 * setBits(X & Y) = M, where ⊕ denotes the Bitwise XOR and & denotes the Bitwise AND. Examples: Input: arr[] = {30, 0, 4, 5 }, M = 2Output: 2Exp
14 min read
Flip consecutive set bits starting from LSB of a given number
Given a positive integer N, the task is to find the number that can be obtained by flipping consecutive set bits starting from the LSB in the binary representation of N. Examples: Input: N = 39Output: 32Explanation:Binary representation of (39)10 = (100111)2After flipping all consecutive set bits starting from the LSB, the number obtained is (10000
6 min read
Count minimum bits to flip such that XOR of A and B equal to C
Given a sequence of three binary sequences A, B and C of N bits. Count the minimum bits required to flip in A and B such that XOR of A and B is equal to C. For Example : Input: N = 3 A = 110 B = 101 C = 001 Output: 1 We only need to flip the bit of 2nd position of either A or B, such that A ^ B = C i.e., 100 ^ 101 = 001 A Naive approach is to gener
10 min read
Minimum flips required to form given binary string where every flip changes all bits to its right as well
Given a string S, the task is to find minimum flips required to convert an initial binary string consisting of only zeroes to S where every flip of a character flips all succeeding characters as well. Examples: Input: S = "01011" Output: 3 Explanation: Initial String - "00000" Flip the 2nd bit - "01111" Flip the 3rd bit - "01000" Flip the 4th bit -
4 min read
Flip all K-bits of a given number
Given two integers N and K, the task is to represent N in K bits and print the number obtained after flipping all the bits. Examples: Input:N = 1, K = 32Output: 4294967294Explanation:1 in K(= 32) bit representation is (00000000000000000000000000000001)2.Flipping all the bits modifies N to (11111111111111111111111111111110)2 = (4294967294)10. Input:
3 min read
Sum of numbers obtained by the count of set and non-set bits in diagonal matrix elements
Given a square matrix mat[][] of dimension N*N, convert the elements present in both the diagonals to their respective binary representations and perform the following operations: For every position of bits, count the number of set bits and non-set bits in those binary representations.If count of set bits exceeds that of non-set bits, place 0 at th
10 min read
Check if all bits can be made same by single flip
Given a binary string, find if it is possible to make all its digits equal (either all 0's or all 1's) by flipping exactly one bit. Input: 101Output: YeExplanation: In 101, the 0 can be flipped to make it all 1 Input: 11Output: NoExplanation: No matter whichever digit you flip, you will not get the desired string. Input: 1Output: YesExplanation: We
5 min read
Print numbers having first and last bits as the only set bits
Given a positive integer n. The problem is to print numbers in the range 1 to n having first and last bits as the only set bits.Examples: Input : n = 10 Output : 1 3 5 9 (1)10 = (1)2. (3)10 = (11)2. (5)10 = (101)2. (9)10 = (1001)2 Naive Approach: Print "1". Now for i = 3 to n, check if (i-1) is a Perfect power of two or not. If true then print i. C
10 min read
Count total set bits in first N Natural Numbers (all numbers from 1 to N)
Given a positive integer N, the task is to count the total number of set bits in binary representation of all natural numbers from 1 to N. Examples: Input: N = 3Output: 4Explanation: Numbers from 1 to 3: {1, 2, 3}Binary Representation of 1: 01 -> Set bits = 1Binary Representation of 2: 10 -> Set bits = 1Binary Representation of 3: 11 -> Se
15+ min read
Check if bits of a number has count of consecutive set bits in increasing order
Given a integer n > 0, the task is to find whether in the bit pattern of integer count of continuous 1's are in increasing from left to right. Examples : Input:19 Output:Yes Explanation: Bit-pattern of 19 = 10011, Counts of continuous 1's from left to right are 1, 2 which are in increasing order. Input : 183 Output : yes Explanation: Bit-pattern
11 min read
Numbers formed by flipping common set bits in two given integers
Given two positive integers A and B, the task is to flip the common set bitsin A and B. Examples: Input: A = 7, B = 4 Output: 3 0 Explanation: The binary representation of 7 is 111 The binary representation of 4 is 100 Since the 3rd bit of both A and B is a set bit. Therefore, flipping the 3rd bit of A and B modifies A = 3 and B = 0 Therefore, the
8 min read
Minimize cost of swapping set bits with unset bits in a given Binary string
Given a binary string S of size N, the task is to find the minimum cost by swapping every set bit with an unset bit such that the cost of swapping pairs of bits at indices i and j is abs(j - i). Note: A swapped bit can't be swapped twice and the count of set bit in the given binary string is at most N/2. Examples: Input: S = "1010001"Output: 3Expla
12 min read
Count numbers formed by given two digit with sum having given digits
Given a, b and N(1 to 106). Task is to count the numbers formed by digits a and b exactly of a length N such that the sum of the digits of the number thus formed also contains digits a and b only. Since the count can be very large, print the count % 1000000007. Examples : Input : a = 1 b = 3 n = 3 Output : 1 Explanation : The only number is 111 of
15 min read
Check if all bits can be made same by flipping two consecutive bits
Given a binary string, the task is to find whether all the digits of the string can be made equal i.e either 0 or 1 by flipping two consecutive bits any number of times.Examples: Input: 01011Output: YESExplanation:Flip 2nd and 3rd bit -> 00111, again flipping 1'st and 2'nd bit -> 11111 Input: 100011Output: NOExplanation:No number of moves can
5 min read
Range queries to count 1s in a subarray after flip operations
Given an array 'arr' all the numbers of which are initialized to '0' then the array can be updated at any time in the following way: All the elements of any sub-array from the array can be flipped i.e. '1' => '0' or '0' => '1'. The task is to find the number of 1s from the array for any incoming query [l, r] where 'l' and 'r' are valid indice
15 min read
Count Number of Distinct Binary Strings After Applying Flip Operations
Given a binary string s and a positive integer k. In a operation you can repeatedly choose any substring of length k in s and flip all its characters (0s to 1s, 1s to 0s). The task is to return the number of distinct strings that can be obtained, modulo 10^9 + 7. You can perform the flip operation any number of times. Example: Input: s = "1001", k
5 min read
Count prime numbers up to N that can be represented as a sum of two prime numbers
Given a positive integer N, the task is to find the count of prime numbers less than or equal to N that can be represented as a sum of two prime numbers. Examples: Input: N = 6Output: 1Explanation:5 is the only prime number over the range [1, 6] that can be represented as sum of 2 prime numbers i.e., 5 = 2 + 3, where 2, 3 and 5 are all primes.There
15+ min read
Flip minimum signs of array elements to get minimum sum of positive elements possible
Given an array of positive elements, you have to flip the sign of some of its elements such that the resultant sum of the elements of array should be minimum non-negative (as close to zero as possible). Return the minimum no. of elements whose sign needs to be flipped such that the resultant sum is minimum non-negative. Note that the sum of all the
12 min read
Print first n numbers with exactly two set bits
Given a number n, print first n positive integers with exactly two set bits in their binary representation.Examples : Input: n = 3Output: 3 5 6The first 3 numbers with two set bits are 3 (0011),5 (0101) and 6 (0110)Input: n = 5Output: 3 5 6 9 10 12A Simple Solution is to consider all positive integers one by one starting from 1. For every number, c
11 min read
Check if it is possible to make given two numbers equal or not by changing 1 bit or 2 bits once
Given two positive integers A and B, perform one of the following operations only once to make the numbers equal. Change the ith bit of a number to 0 or 1Change the ith bit to 0 or 1 in A and jth bit to 0 or 1 in B If it’s possible to make the numbers equal, then print "Yes". Otherwise, print "No". Examples: Input: A = 5, B = 15Output: YesExplanati
9 min read
Queries to flip characters of a binary string in given range
Given a binary string, str and a 2D array Q[][] representing queries of the form {L, R}. In each query, toggle all the characters of the binary strings present in the indices [L, R]. The task is to print the binary string by performing all the queries. Examples: Input: str = "101010", Q[][] = { {0, 1}, {2, 5}, {2, 3}, {1, 4}, {0, 5} } Output: 11100
8 min read
Flip all 0s in given Binary Strings K times with different neighbours
Given a binary string S of size N and a positive integer K, the task is to repeatedly modify the given string K number of times by flipping all the 0s having different adjacent characters in each iteration. Note: For the character 0 present at 0th index then it will change to 1 only when 1st index character is 1 and if the last index character is 0
8 min read
Flip the String by either swapping given characters or rotating it horizontally for Q queries
Given a string S of length 2N and Q Queries containing three integers T, A, and B each, where queries can be of the following two types: T=1: Swap the Ath and Bth characters in S.(In 1-based indexing)T=2: Swap the first N characters with the last N characters i.e "ABCD" becomes "CDAB" The task is to find the final string after applying the Q Querie
15 min read
Flip the given Matrix along both diagonals in clockwise direction
Given a matrix arr[][] of size M*N, where M is the number of rows and N is the number of columns. The task is to flip the matrix by both diagonals. Flipping the matrix means rotating all elements of the matrix in a clockwise direction, along the diagonal. Examples: Input: arr[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }Output: { {9, 8, 7}, {6, 5, 4},
6 min read
Python map function | Count total set bits in all numbers from 1 to n
Given a positive integer n, count the total number of set bits in binary representation of all numbers from 1 to n. Examples: Input: n = 3 Output: 4 Binary representations are 1, 2 and 3 1, 10 and 11 respectively. Total set bits are 1 + 1 + 2 = 4. Input: n = 6 Output: 9 Input: n = 7 Output: 12 Input: n = 8 Output: 13 We have existing solution for t
2 min read
Count of numbers whose 0th and Nth bits are set
Given a positive integer N, the task is to count the numbers that can be represented with N bits and whose 0th and Nth bits are set. Examples: Input: N = 2 Output: 1 All possible 2-bit integers are 00, 01, 10 and 11. Out of which only 11 has 0th and Nth bit set.Input: N = 4 Output: 4 Approach: Out of the given N bits, only two bits need to be set i
3 min read
Count set bits in the Kth number after segregating even and odd from N natural numbers
Given two integers N and K, the task is to find the count of set bits in the Kth number in the Odd-Even sequence made of the number from the range [1, N]. The Odd-Even sequence first contains all the odd numbers from 1 to N and then all the even numbers from 1 to N.Examples: Input: N = 8, K = 4 Output: 3 The sequence is 1, 3, 5, 7, 2, 4, 6 and 8. 4
6 min read
Count total set bits in all numbers from range L to R
Given two positive integers L and R, the task is to count the total number of set bits in the binary representation of all the numbers from L to R. Examples: Input: L = 3, R = 5 Output: 5 Explanation: (3)10 = (11)2, (4)10 = (100)2, (5)10 = (101)2 So, Total set bit in range 3 to 5 is 5 Input: L = 10, R = 15 Output: 17 Method 1 - Naive Approach: The
15+ min read
Count numbers in the range [L, R] having only three set bits
Given an array arr[] of N pairs, where each array element denotes a query of the form {L, R}, the task is to find the count of numbers in the range [L, R], having only 3-set bits for each query {L, R}. Examples: Input: arr[] = {{11, 19}, {14, 19}}Output: 4 2Explanation: Query(11, 19): Numbers in the range [11, 19] having three set bits are {11, 13,
9 min read
Count numbers in range [L, R] having K consecutive set bits
Given three positive integers l, r, and k, the task is to find the count of numbers in the range [l, r] having k consecutive set bits in their binary representation. Examples: Input: l = 4, r = 15, k = 3 Output: 3 Explanation: Numbers whose binary representation contains k=3 consecutive set bits are: (7)10 = (111)2 (14)10 = (1110)2 (15)10 = (1111)2
13 min read
  翻译: