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