1. 程式人生 > >231. 2的冪 | Power of Two

231. 2的冪 | Power of Two

only add credit ive mine 示例 edit UNC bsp

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 }

231. 2的冪 | Power of Two