Simply take binary of the given number and check for number of occurrences of ‘1’ in that binary string.if that count equals to 1 then it’s a power of 2 otherwise not.you can check occurrences easily just by calling a simple function in java.
The solution i have provided is simpler i guess…
Also we could modify your solution to check till no of 1’s is < 2 then stop. If it stops before reaching end of string then its isn’t a power of 2 else it is. This decreases time complexity for the code.
N.B. - Above isn’t a question but a solution to find if a no power of 2.
You can take log(to base 10) and take mod 0.301 (log 2). If the mod is zero then the no. is a power of 2 which is log(no.)/0.301.
n = log10(n) ;
if (n % 0.301 == 0) then
power of 2 ;