-
-
Notifications
You must be signed in to change notification settings - Fork 51
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
checks given number is power of 2 or not
- Loading branch information
1 parent
1eddf3c
commit 4273f1e
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
|
||
} |