Swap bits in a given number |  ; Setting bit at p1 position to 1 ; Setting bit at p2 position to 1 ; value1 and value2 will have 0 if num at the respective positions - p1 and p2 is 0. ; check if value1 and value2 are different i . e . at one position bit is set and other it is not ; if bit at p1 position is set ; unset bit at p1 position ; set bit at p2 position ; if bit at p2 position is set ; set bit at p2 position ; unset bit at p2 position ; return final result ; Driver code
def swapBits ( num , p1 , p2 , n ) : NEW_LINE INDENT shift1 = 0 NEW_LINE shift2 = 0 NEW_LINE value1 = 0 NEW_LINE value2 = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT shift1 = 1 << p1 NEW_LINE shift2 = 1 << p2 NEW_LINE value1 = ( ( num & shift1 ) ) NEW_LINE value2 = ( ( num & shift2 ) ) NEW_LINE if ( ( value1 == 0 and value2 != 0 ) or ( value2 == 0 and value1 != 0 ) ) : NEW_LINE INDENT if ( value1 != 0 ) : NEW_LINE INDENT num = num & ( ~ shift1 ) NEW_LINE num = num | shift2 NEW_LINE DEDENT else : NEW_LINE INDENT num = num & ( ~ shift2 ) NEW_LINE num = num | shift1 NEW_LINE DEDENT DEDENT p1 += 1 NEW_LINE p2 += 1 NEW_LINE n -= 1 NEW_LINE DEDENT return num NEW_LINE DEDENT res = swapBits ( 28 , 0 , 3 , 2 ) NEW_LINE print ( " Result ▁ = " , res ) NEW_LINE