power of n

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.









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值