We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Since you want explanation with an example, I'll explain it with 221 because 13 won't help much. Now, binary represention of 221 is 11011101. Visualizing iterations of while-loop using binary clarifies the procedure :
First Iteration : n 11011101
n<<1 110111010
n & (n<<1) 10011000
Second Iteration : n 10011000
n<<1 100110000
n & (n<<1) 10000
Third Iteration : n 10000
n<<1 100000
n & (n<<1) 0
As the above example shows, number of consecutive 1's in n reduce by one in every iteration of while-loop. Thus, counting the iterations, gives the required answer.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Consecutive 1's in Binary Numbers
You are viewing a single comment's thread. Return to all comments →
Other than I/O, all operations stay as it is, in Java. Here's Java version for you :
Since you want explanation with an example, I'll explain it with
221
because13
won't help much. Now, binary represention of221
is11011101
. Visualizing iterations ofwhile-loop
using binary clarifies the procedure :As the above example shows, number of consecutive
1
's in n reduce by one in every iteration ofwhile-loop
. Thus, counting the iterations, gives the required answer.