Sambit Mishra - 2 months ago 6

Python Question

I got a program where any binary number is considered and with 1 flip of either 0 or 1, if we get all 0s or all 1s, then it returns true else it will return false.

For e.g. 110 on 1 flip of element 0 returns 111 and it is printed as true.

111 is a binary number which on one flip, is printed as false.

Any possible solution of how to solve it?

Looking forward to the best possible solutions. Appreciate if the solution is written using Python.

This is what i had actually done.

`def binary(num, length = 4):`

return format(num, '#0{}b'.format(length + 2)).replace('0b', '')

n = binary(125)

n.count('0')

n.count('1')

if (n.count('0') == 1) or (n.count('1') == 1):

return true

Actually I had no idea of how to flip it.

Answer

So you need to determine whether binary representation of given number contains only one "one" or only one "zero"? There is bit trick to find numbers with single bit set:

```
if (x == 0)
return false
if (x & (x - 1) == 0
return true
```

Explanation: if number looks like `b00001000`

, then decrement gives `b00000111`

and binary AND leads to zero result

For checking single-zero numbers just invert them

if there is no `~`

operator (binary NOT) in Python, you can invert all bits of number with

```
x_inversion = -(x+1)
```

Source (Stackoverflow)

Comments