java - determine whether an int is power of 2 -
this question has answer here:
- how check if number power of 2 22 answers
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
Post a Comment