231. 2的幂 | Power of Two

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


给定一个整数,编写一个函数来判断它是否是 2 的幂次方。

示例 1:

输入: 1
输出: true
解释: 20 = 1

示例 2:

输入: 16
输出: true
解释: 24 = 16

示例 3:

输入: 218
输出: false

24ms
 1 class Solution {
 2     func isPowerOfTwo(_ n: Int) -> Bool {
 3         if n < 1 {return false}
 4         var num:Int = n
 5         while (num != 1)
 6         {
 7             if num%2 == 1 {return false}
 8             else { num /= 2}
 9         }
10         return true
11     }
12 }

24ms

 1 class Solution {
 2     func isPowerOfTwo(_ n: Int) -> Bool {
 3        guard n > 0 else { return false }
 4         if n == 1 { return true }
 5         var num = 2
 6         while num < n {
 7             num *= 2
 8         }
 9         return num == n
10     }
11 }
 1 class Solution {
 2     func isPowerOfTwo(_ n: Int) -> Bool {
 3        guard n > 0 else { return false }
 4         if n == 1 { return true }
 5         var num = 2
 6         while num < n {
 7             num *= 2
 8         }
 9         return num == n
10     }
11 }

20ms

 1 class Solution {
 2     func isPowerOfTwo(_ n: Int) -> Bool {
 3         if n == 1 {
 4             return true
 5         }
 6         
 7         var x : Int = 2
 8         while (x <= n)       
 9         {
10             if x == n {
11                 return true
12             }
13             
14             x *= 2
15         }
16         return false
17     }
18 }

20ms

1 class Solution {
2     func isPowerOfTwo(_ n: Int) -> Bool {
3         // Power of two means that only one bit is '1'
4         return n.nonzeroBitCount == 1
5     }
6 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/9748094.html