What is the most efficient way to check if x or x bar as more ones?

75 Views Asked by At

For example, taking the number x=74, which in boolean is 1001010 . I denote x_bar as x_bar= 0110101. Here we see that x_bar has more ones.

1

There are 1 best solutions below

5
On

The closer to a power of $2$ the number $x$ is "from below", the more ones it has. You can compute the distance $x$ has to the next power of $2$ by finding $2^{\lfloor\log_2x\rfloor+1}-x$.

For example, $60$ is $4$ away from the next power of $2$. Indeed, $2^{\lfloor\log_260\rfloor+1}-60=4$.

So a possible solution is to compute the distance for $x$ and $\bar x$, and see which is smaller. I'm not sure how you're computing $\bar x$ (in particular, how do you deal with leading zeros, are they fixed length?)