首页 > 学院 > 开发设计 > 正文

LeetCode-231. Power of Two

2019-11-08 01:26:03
字体:
来源:转载
供稿:网友

问题:https://leetcode.com/PRoblems/power-of-two/?tab=Description Given an integer, write a function to determine if it is a power of two. 给定一个数,判断它是不是2的幂数。 分析:二进制来说,2的幂数都是首位是1,其他位是0。所以用n&(n-1)是否为0可以判断。 C++中&&是且,&是按位与。 C++代码:

class Solution {public: bool isPowerOfTwo(int n) { return (n>0) && ((n&(n-1))==0);//&&是且的意思,&是按位与。 }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表