New way to find smallest on bit

Revision en1, by XoXoHarsh, 2023-02-19 06:18:48

I was solving a problem — "Minimum number of power of 2 to get an integer". for example, if the integer is 15 we can get it by 2^4-2^0. I searched for an online solution and found an exciting way to get the smallest bit, which is on.

Variable&-Variable

e.g. int val=39 cout<<(val&-val) Output — 1 (since 1st bit is on or you can say true)

I certainly do not know how this works but after testing it I am sure it gives the smallest bit which is on in the Variable. If someone knows how this works please comment below. Thank you Enjoy coding :)

Tags bit manipulation, bitwise, #innovation, learning

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English XoXoHarsh 2023-02-19 06:18:48 615 Initial revision (published)