Can someone please explain how the binary number is being reversed.
unsigned rev = 0;
unsigned k = n;
while (k)
{
// add rightmost bit to rev
rev = (rev << 1) | (k & 1);
k = k >> 1; // drop last bit
cout<<"k val is "<<bitset<8>(k)<<endl;
cout<<"rev val is "<<{bitset<8>(rev)<<endl;
}
Output if n=9
k val is 00000100
rev val is 00000001
k val is 00000010
rev val is 00000010
k val is 00000001
rev val is 00000100
k val is 00000000
rev val is 00001001
9 is Palindrome
I was referring question 2 from here: http://www.techiedelight.com/bit-hacks-part-6-random-problems/
As far as I know, only first expression is executed if it is true for “|” condition statement. So, here rev<<1 will be false only for first execution of loop but not for rest. Therefore how does rev get 1 in the end for last condition because (k&1) won’t be executed. Only left shift will be executed right?