All the numbers which are the power of 2 will only have 1 set bit (1) and the rest all unset bit (0). And ( & ) of number and 1 integer less then that will result in 0.
package org.wesome.dsalgo;
public class CheckPowerOf2 {
public static boolean powerOf2(int number) {
int less = number - 1;
System.out.println(number + " In binary will be " + Integer.toBinaryString(number) + ", " + less + " In binary will be " + Integer.toBinaryString(less));
int result = (number & less);
boolean isPowerOf2 = (result == 0);
System.out.println("result is " + result + ", number " + number + " is power of 2 = " + isPowerOf2);
return isPowerOf2;
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class CheckPowerOf2Test {
@Test
void checkPowerOf2Test1() {
Assertions.assertTrue(CheckPowerOf2.powerOf2(4));
}
@Test
void checkPowerOf2Test2() {
Assertions.assertFalse(CheckPowerOf2.powerOf2(6));
}
@Test
void checkPowerOf2Test3() {
Assertions.assertTrue(CheckPowerOf2.powerOf2(8));
}
}
plugins {
id 'java'
id "io.freefair.lombok" version "6.2.0"
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}