Search code examples
pythonpython-3.xbit-manipulationxor

For how many values of x will n + x = n XOR x when n and x are whole numbers and n>=x?


Note:The contest is over.I just want to know other way to solve this

n = int(input())
if n == 0:
    print('1')
else:
    print(1<<(str(bin(n)).count('0') - 1)) 

Chef has studied 2- bit Binary Adder in his Digital Logic Design class. He is amazed by the XOR operator and he believes that a + b = a xor b, where a and b are whole numbers and xor is Bitwise XOR operator.

Chef's teacher's favorite number is n. Chef's teacher is in angry mood and he gives Chef a whole number x (x <= n) and asks Chef to compute n + x to test his Binary Addition understanding. Chef answers n xor x.

Input A single integer n.

sample input:0 sample output:1

sample input:5 sample output:2


Solution

  • Suggested solution:

    n = int(input())
    if n == 0:
        print('1')
    else:
        print(pow(2, (str(bin(n)).count('0')-1)))
    

    when n = 0 it prints 1 and when n = 5 it outputs 2 and etc.

    It's doing the same thing the solution above is doing: counting the number of zeros, k, in the binary representation of n, ignoring the leading zero, and returns 2k as an answer because any integer x that has any number of these bits turned on - will qualify for n ^ x == n + x