Leetcode之Power of Two
作者:互联网
题目:
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false
代码:
方法一——常规思路,时间复杂度O(logN):
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0)return false;
if(n==1)return true;
if(n%2!=0)return false;
return isPowerOfTwo(n/2);
}
};
方法二——利用位运算的性质,时间复杂度O(1):
class Solution {
public:
bool isPowerOfTwo(int n) {
return n>0&&!(n&(n-1));
}
};
一只荣 发布了312 篇原创文章 · 获赞 25 · 访问量 2万+ 私信 关注
标签:Power,int,复杂度,Explanation,Two,Leetcode,Input,Output,Example 来源: https://blog.csdn.net/qq_35455503/article/details/104123926