Reputation: 7540
Is there any way to get n
number of 1
s using only these binary operations ( !
, ~
, &
, ^
, |
, +
, <<
, >>
) where n
is an input?
Example,
n ---> output
0 ---> 0000
1 ---> 0001
2 ---> 0011
3 ---> 0111
4 ---> 1111
...
Upvotes: 2
Views: 116
Reputation: 503
Yes. You can do
~(~(1<<n) + 1)
Example:
Say n is 2.
~(~(1<<2) + 1)
~(~(100) + 1)
~(111..1011 + 1)
~(111..1100 )
= 11
Upvotes: 0
Reputation: 726509
You can do it like this:
// Since "-" is not on your list while "+" is, I'll add negative 1
// using `~0`; this assumes that your computer uses 2's complement
// representation of negative numbers.
(1 << n) + ~0;
The idea is that 1 << n
produces a power of two: 1
, 10
, 100
, 1000
, and so on. Adding a negative one produces 2^n-1
, which is what your pattern represents.
Upvotes: 3