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>You can loop over the values from 0 to log(x) where x is your output and xor with 2<sup>x</sup> which is 100000... Then you just check, whether what you got is 0 or 2<sup>x+1</sup>-1. It should work fine.</p>

<pre><code>def g(x):
    for i in range(int(log(x)/log(2))):
        if x ^ 2 ** i == 0 or x ^ 2 ** i == 2 ** int(log(x)/log(2) + 1) - 1:
            return True
    return False
</code></pre>

<p>Another solution is to sort the binary interpretation of the number and check, whether these is only one 1 or only one 0. The lambda function written below does exactly that. Since <code>bin()</code> returns binary <code>0b</code> followed by the binary interpretation of the number I get rid of it and then, remove all <code>0</code> to check whether there only one <code>1</code>, the second part checks the opposite.</p>

<pre><code>f = lambda x: len(str(bin(x))[2:].replace('0','')) == 1 or len(str(bin(x))[2:].replace('1','')) == 1
</code></pre>

<p>If x is the binary interpretation of the number, you should use this:</p>

<pre><code>f = lambda x: len(x.replace('0','')) == 1 or len(x.replace('1','')) == 1
</code></pre>

python python-3.x math binary