Allows n be 4 , which in binary format is represented as:
00000000 00000000 00000000 00000100
(n&1) bitwise, and n with 1 .
1 has a binary representation:
00000000 00000000 00000000 00000001
Bitwise Result 0 :
00000000 00000000 00000000 00000100 = n 00000000 00000000 00000000 00000001 = 1 ------------------------------------ 00000000 00000000 00000000 00000000 = 0
therefore, the while condition is true.
Effectively (n&1) used to extract the least significant digit n .
In a while loop, you shift right ( >> ) n by 1 . The right shift of the number by k coincides with the division of the number by 2^k .
n , which is now 00000000 00000000 00000000 00000100 with a right offset, once becomes 00000000 00000000 00000000 00000010 , which is 2 .
Then we again extract the least significant bit of the least significant bit n , which is 0 and the right shift to give 00000000 00000000 00000000 0000001 , which is 1 .
Then we again retrieve the LSB from n, which is now 1 , and the loop breaks.
Thus, you continue to divide the number n by 2 until it becomes odd , since the odd numbers have their own LSB set.
Also note that if n is 0 for starters, you will go into an infinite loop, because no matter how many times you divide 0 by 2 , you will not get an odd number.
codaddict
source share