|
| 1 | +packageeasy; |
| 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 | +publicclassPowerOfTwo { |
| 8 | +publicbooleanisPowerOfTwo(intn) { |
| 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)returnfalse; |
| 13 | +return (n&(n-1)) ==0; |
| 14 | + } |
| 15 | + |
| 16 | +publicstaticvoidmain(String...strings){ |
| 17 | +PowerOfTwotest =newPowerOfTwo(); |
| 18 | +System.out.println(test.isPowerOfTwo(14)); |
| 19 | + } |
| 20 | +} |