How to take one's complement of a positive integer?

153 Views Asked by At

Of course we can do that by converting the number to binary and then converting it back to decimal, but to do that directly in decimal?

1

There are 1 best solutions below

2
On BEST ANSWER

You need to fix a maximum number of bits $b$ and then the one's complement of a positive integer $x$ with at most $b$ bits is given by $x'=2^b-1-x$, because by definition the sum $x+x'$ has all bits set and hence is of the form $2^b-1$.

If you do not fix a maximum number of bits then you can still flip all significant bits, but then the map $x\mapsto x'$ is no longer injective (and hence not invertible) because for instance $0$ and $2$ are mapped to $1$.