*Power of Two

mac2022-06-30  93

题目:

Given an integer, write a function to determine if it is a power of two.

 

bn is the product of multiplying n bases:

{\displaystyle b^{n}=\underbrace {b\times \cdots \times b} _{n}}

In that case, bn is called the n-th power of b, or b raised to the power n.

 

 

解法一:bit

如果是power of two, 则2进制表达中,有且仅有一个1.  可以通过移位来数1的个数, 这里用了一个巧妙的办法, 即判断   N & (N-1) 是否为0. 

 

1 public class Solution { 2 public boolean isPowerOfTwo(int n) { 3 return n > 0 && ((n & (n - 1)) == 0 ); 4 } 5 }

 

解法二:可以应用到power of n

public class Solution { public boolean isPowerOfTwo(int n) { if(n>1) { while(n%2==0) { n=n/2; } } return n==1; } }

 

 

reference: http://blog.csdn.net/xudli/article/details/46784163

转载于:https://www.cnblogs.com/hygeia/p/4687800.html

最新回复(0)