Skip to content

Commit

Permalink
checks given number is power of 2 or not
Browse files Browse the repository at this point in the history
  • Loading branch information
NirmalSilwal committed Jul 14, 2020
1 parent 1eddf3c commit 4273f1e
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions CodingBlocks Training/Day8/PowerOf2Check.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Bit-Masking

package Lecture8;

public class PowerOf2Check {

public static void main(String[] args) {

int num = 1;
System.out.println(checkPowerOf2(num));

System.out.println(powerCheck2(num));
}

// 1st approach ~ inefficient one -> O(logn)
public static boolean powerCheck2(int n) {
if (n != 0 && n != 1){
while (n > 1) {
n = n / 2;
// System.out.println(n);
}
if (n == 1) {
return true;
} else {
return false;
}
}
return false;
}

// 2nd approach ~ efficient solution -> O(1)
public static boolean checkPowerOf2(int n) {
if (n != 0 && n != 1) {
if ((n & (n - 1)) == 0) {
return true;
}
}
return false;
}

}

0 comments on commit 4273f1e

Please sign in to comment.