java - determine whether an int is power of 2 -


this question has answer here:

    public class test{     public static void main(string[] args) {     int a=536870912;     system.out.print((math.log(a)/math.log(2))); } } 

536870912 number power of two, result 29.000000000000004, explain this? thanks.

if n power of 2, binary representation start 1 , contain 0s after it.

so, can do:

string binary = integer.tobinarystring(a); pattern poweroftwopattern = pattern.compile("10*"); system.out.println(poweroftwopattern.matcher(binary).matches()); 

anyway, if number not huge (i.e. fits int or long range), can follow suggestions here


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -