sadaf2605
sadaf2605

Reputation: 7540

n number of 1s using binary operations

Is there any way to get n number of 1s 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

Answers (2)

anshul garg
anshul garg

Reputation: 503

Yes. You can do

~(~(1<<n) + 1)

Example:

Say n is 2.

  1. ~(~(1<<2) + 1)

  2. ~(~(100) + 1)

  3. ~(111..1011 + 1)

  4. ~(111..1100 )

    = 11

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

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

Related Questions