See if a number is power of 2, then only one bit in the number will be set. e.g. for 16, 00010000 assuming 8-bit representation. then when you subtract 1 from this number, the bits to the right of the previously set bit will be set, and the set bit will become unset. e.g. 16 will become 15, 00001111.
Take bitwise and, th result will be 0 if it is a power of 2. taking Logical NOT will give 1. Hence the result. Sanju :) On Sat, Aug 20, 2011 at 3:45 AM, SANDEEP CHUGH <[email protected]>wrote: > explain it plz > > > On Sat, Aug 20, 2011 at 4:09 PM, Abhishek Yadav < > [email protected]> wrote: > >> got it ...thanks >> >> >> On Sat, Aug 20, 2011 at 4:04 PM, Sanjay Rajpal <[email protected]> wrote: >> >>> if(!(x & x-1)) printf("No. is power of 2"); >>> >>> >>> Sanju >>> :) >>> >>> >>> >>> On Sat, Aug 20, 2011 at 3:32 AM, Abhishek Yadav < >>> [email protected]> wrote: >>> >>>> Give a one-line C expression to test whether a number is a power of 2. >>>> >>>> -- >>>> You received this message because you are subscribed to the Google >>>> Groups "Algorithm Geeks" group. >>>> To post to this group, send email to [email protected]. >>>> To unsubscribe from this group, send email to >>>> [email protected]. >>>> For more options, visit this group at >>>> http://groups.google.com/group/algogeeks?hl=en. >>>> >>>> >>> -- >>> You received this message because you are subscribed to the Google Groups >>> "Algorithm Geeks" group. >>> To post to this group, send email to [email protected]. >>> To unsubscribe from this group, send email to >>> [email protected]. >>> For more options, visit this group at >>> http://groups.google.com/group/algogeeks?hl=en. >>> >> >> -- >> You received this message because you are subscribed to the Google >> Groups "Algorithm Geeks" group. >> To post to this group, send email to [email protected]. >> To unsubscribe from this group, send email to >> [email protected]. >> For more options, visit this group at >> http://groups.google.com/group/algogeeks?hl=en. >> > > -- > You received this message because you are subscribed to the Google Groups > "Algorithm Geeks" group. > To post to this group, send email to [email protected]. > To unsubscribe from this group, send email to > [email protected]. > For more options, visit this group at > http://groups.google.com/group/algogeeks?hl=en. > -- You received this message because you are subscribed to the Google Groups "Algorithm Geeks" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/algogeeks?hl=en.
