program to find All numbers y , less than a number x having the bits set at places only where they are set in x.

30 Views Asked by At

consider for example 118 its binary representation is 1110110. I want to have all numbers that have bits set at places only at places where it is set in 118 as follows:

  • 114->1110010
  • 112->1110000
  • 102->1100110
  • 98->1100010 and so on upto
  • 20->0010100
  • 6->0000110.
  • 2->0000010
  • 0->0000000

I want to write an efficient c++ program for the list of numbers. Thanks in advance.

1

There are 1 best solutions below

3
On

Why not $2$? Why not $0$? Count the bits turned on in your starting number, $5$ in $118$. Count from $0$ to $2^5-1$ in binary and use that to indicate which bits should be on. If you count downward they will come out in downward order like you indicate. If you don't want to include $0$, stop counting at $1$.