Power of 2
return (n&(n-1)) ==0;
n & (n-1)==0 is executed as n & ((n-1)==0)
See https://en.wikipedia.org/wiki/OperatorsinCandC%2B%2B
class Solution {
public:
bool isPowerOfTwo(int n) {
return ((n & (n- 1)) == 0 && (n > 0)) ? true : false;
}
};
Power of 3
<span style="font-size:14px;">class Solution {
public:
bool isPowerOfThree(int n) {
while ((n/3) != 0)
{
if ((n%3) != 0)
{
return false;
}
n = n / 3;
}
return (n == 1 ) ? true : false;
}
};</span>
Do it without any recursion or loop
https://leetcode.com/discuss/78532/summary-all-solutions-new-method-included-at-15-30pm-jan-8th
Power of 3
Rounds the specified uint 'value' up to the nearest value meeting the specified 'alignment'. Only power of 2 alignments are supported
return ((value + (alignment) - 1) & ~((alignment) - 1));
Determines if 'value' is at least aligned to the specified power-of-2 alignment.