Return true if a binary number either contains all zero or all ones on a single flip.(Python)
<p>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. </p>

<p>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?</p>

<p>Looking forward to the best possible solutions. Appreciate if the solution is written using Python.</p>

<p>This is what i had actually done.</p>

<pre><code>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
</code></pre>

<p>Actually I had no idea of how to flip it. </p>

<p>Just for laughs - with some bitwise manipulations:</p>

<pre><code>&gt;&gt;&gt; def single_flip(n):
...    return any(x and not x &amp; (x - 1) for x in [n, n^2**n.bit_length()-1])])
...
&gt;&gt;&gt; single_flip(0b1110111), single_flip(0b1010111), single_flip(0b0001000)
(True, False, True)
</code></pre>

<p>This just tests whether the number or its bitwise complement (not 2's complement) are a factor of 2.</p>

python python-3.x math binary