Calculating the next higher number which has same number of set bits?

后端 未结 3 479
不思量自难忘°
不思量自难忘° 2021-01-17 06:35

A solution is given to this question on geeksforgeeks website.

I wish to know does there exist a better and a simpler solution? This is a bit complicated to understa

3条回答
  •  清歌不尽
    2021-01-17 06:54

    There is a simpler, though definitely less efficient one. It follows:

    • Count the number of bits in your number (right shift your number until it reaches zero, and count the number of times the rightmost bit is 1).
    • Increment the number until you get the same result.

    Of course it is extremely inefficient. Consider a number that's a power of 2 (having 1 bit set). You'll have to double this number to get your answer, incrementing the number by 1 in each iteration. Of course it won't work.

    If you want a simpler efficient algorithm, I don't think there is one. In fact, it seems pretty simple and straightforward to me.

    Edit: By "simpler", I mean it's mpre straightforward to implement, and possibly has a little less code lines.

提交回复
热议问题