1

There is a sequence of increasing numbers that have the same number of binary 1s in them. Given n (the number of 1 bits set in each number in the series) write an algorithm or C program to find the n'th number in the series.

I found this question on internet and I think the answer is just (((1 << (n+1)) - 1) & ~2). Isn't that right? I found some scary programs to compute the answer.

Anil Katti
  • 1,313
  • 1
  • 14
  • 26

4 Answers4

5

(1 << n+1) - 3 is a more concise way to express the result, but yes, I believe your expression is also correct.

Stephen Canon
  • 103,815
  • 19
  • 183
  • 269
1

Yes, it's true. When we have 3 bits:

1:  00000111
2:  00001011
3:  00001101 // bit 1 will be 0
4:  00001110

so the answer is n+1 bits, where bit 1 is 0.

ruslik
  • 14,714
  • 1
  • 39
  • 40
  • His formula, for n=3, gives 13. This is the number you list in line 3, so his formula looks right to me. krakover's formula is incorrect. – Martin v. Löwis Jan 04 '11 at 23:43
  • No ruslik, in this case my expression will yield 00001101 - won't it? (((1 << 4) - 1) & (11111101)) = 00001101 – Anil Katti Jan 04 '11 at 23:46
0

I believe you are right. A simpler way to write it though will be: ((1 << n) - 1) << 1.

krakover
  • 2,989
  • 2
  • 27
  • 29
-1

The question doesn't seem to specify where the sequence begins, or how much the number will increase each time, whereas your answer appears to assume that the sequence will start with 011111, then move to 101111, and so on. It could conceivably start with 0011111000, and the next element could be 1111100000.

Edit

The question, as stated at https://groups.google.com/group/algogeeks/browse_thread/thread/5fda06c0be475c41/ is titled, "nth number of the series", so the title of this post ("nth smallest number with n bits set to 1") isn't really in keeping the the question's origin.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • 1
    No: for 5 bits, 11111 is clearly a number in the sequence, and it is clearly smaller than 0011111000. So the sequence can't start with 0011111000. – Martin v. Löwis Jan 04 '11 at 23:45
  • It's the nth smallest integer with n bits set to 1. To be more specific it should have been unsigned integer. – Anil Katti Jan 04 '11 at 23:47
  • The question states, "There is a sequence of increasing numbers that have the same number of binary 1s in them." It doesn't tell you that the sequence must start with the smallest possible number. It's not the same as saying "Sequence S is defined as all positive numbers with the same number of binary 1s in them, in ascending order." – StriplingWarrior Jan 04 '11 at 23:49
  • @Anil Katti: Was it defined that way in the question you read online, or is that just how you understood it? – StriplingWarrior Jan 04 '11 at 23:58
  • @ StriplingWarrior, the question that I found did not have "smallest" in it. I added it when I posted it here since it made more sense. – Anil Katti Jan 05 '11 at 01:05