231. Power of Two
Problem:
Given an integer, write a function to determine if it is a power of two.
Analysis:
Base 2 representation of 2 is 10, 4 is 100, 8 is 1000.
100
&011
--------
000
If a number is power of 2, it qualifies the property that n & (n - 1) == 0
Solution:
Given an integer, write a function to determine if it is a power of two.
Analysis:
Base 2 representation of 2 is 10, 4 is 100, 8 is 1000.
100
&011
--------
000
If a number is power of 2, it qualifies the property that n & (n - 1) == 0
Solution:
class Solution { public boolean isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; } }
评论
发表评论