Yahoo Interview Question Software Engineer / Developers
0of 0 votesLet f(k) = y where k is the y-th number in the increasing sequence of non-negative integers with the
same number of ones in its binary representation as y, e.g. f(0) = 1, f(1) = 1, f(2) = 2, f(3) = 1,
f(4) = 3, f(5) = 2, f(6) = 3 and so on. Given k >= 0, compute f(k).

Use recursion.
- Dumbo on September 28, 2010 Edit | Flag ReplyBase case- f(k): if k has binary digits with all 1s aligned to the right,(and all 0s to the left) return 1;
Recursion- f(k) : return 1 + f(next_lesser_num(k))
next_lesser_num(k) = start from LSD. keep going to the left until you encounter a 0. Now, keep going to the left until to encounter a 1. Flip this 1 to 0 and the zero to the immediate right to 1.