Skip to content

Commit c712926

Browse files
power of two
1 parent fa20b63 commit c712926

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

EASY/src/easy/PowerOfTwo.java

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package easy;
2+
/**231. Power of Two QuestionEditorial Solution My Submissions
3+
Total Accepted: 90169
4+
Total Submissions: 237048
5+
Difficulty: Easy
6+
Given an integer, write a function to determine if it is a power of two.*/
7+
public class PowerOfTwo {
8+
public boolean isPowerOfTwo(int n) {
9+
//after writing out the binary representation of some numbers: 1,2,4,8,16,32, you can easily figure out that
10+
//every number that is power of two has only one bit that is 1
11+
//then we can apply that cool trick that we learned from {@link easy.NumberOfIBits}: n&(n-1) which will clear the least significant bit in n to zero
12+
if(n <= 0) return false;
13+
return (n&(n-1)) == 0;
14+
}
15+
16+
public static void main(String...strings){
17+
PowerOfTwo test = new PowerOfTwo();
18+
System.out.println(test.isPowerOfTwo(14));
19+
}
20+
}

0 commit comments

Comments
 (0)