java - Determine if a number is power of 4, logNum % logBase == 0 vs (logNum / logBase) % 1 == 0 -
problem: check if number power of 4.
my solution in java:
public static boolean ispoweroffour(int num) { return (math.log(num) % math.log(4) == 0); }
but seems off in cases, example when num 64.
i found out if change code little bit, works well.
public static boolean ispoweroffour(int num) { return (math.log(num) / math.log(4) %1 == 0); }
i think both solutions same thing, check if remaining of lognum/logbase 0. why first solution doesn't work? because solution incorrect or relative low level jvm stuff? thanks.
building on @dasblinkenlight's answer, can combine both conditions (first, power of 2, power of 4 among possible powers of 2) simple mask:
public static boolean ispoweroffour(int num) { return ((( num & ( num - 1 )) == 0 ) // check whether num power of 2 && (( num & 0xaaaaaaaa ) == 0 )); // make sure it's power of 2 }
no loop, no conversion float.
Comments
Post a Comment