<div class="image-package"><img src="https://img.haomeiwen.com/i1648392/2058de421fdedf16.jpg" contenteditable="false" img-data="{"format":"jpeg","size":222359,"height":900,"width":1600}" class="uploaded-img" style="min-height:200px;min-width:200px;" width="auto" height="auto"/>
</div><blockquote><p>给你一个整数 n,请你判断该整数是否是 2 的幂次方。如果是,返回 true ;否则,返回 false 。
如果存在一个整数 x 使得 n == 2x ,则认为 n 是 2 的幂次方。
示例 1:
输入:n = 1
输出:true
解释:20 = 1
示例 2:
输入:n = 16
输出:true
解释:24 = 16
示例 3:
输入:n = 3
输出:false
示例 4:
输入:n = 4
输出:true
示例 5:
输入:n = 5
输出:false
提示:
-231 <= n <= 231 - 1
进阶:你能够不使用循环/递归解决此问题吗
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/power-of-two
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。</p></blockquote><p>
</p><h1 id="9hv0t">题解:</h1><h2 id="jgy5v">Swift</h2><p>1.循环</p><div class="image-package"><img src="https://img.haomeiwen.com/i1648392/a55ecc65e8f7557f.jpg" contenteditable="false" img-data="{"format":"jpeg","size":18089,"height":274,"width":761}" class="uploaded-img" style="min-height:200px;min-width:200px;" width="auto" height="auto"/>
</div><blockquote><p>class Solution {
func isPowerOfTwo(_ n: Int) -> Bool {
guard n > 0 else {
return false
}
var n = n
while n % 2 == 0 {
n /= 2
}
return n == 1
}
}
</p></blockquote><p>
</p><p>2.位运算.</p><p><b>数学之美,诚不欺我.</b>
</p><div class="image-package"><img src="https://img.haomeiwen.com/i1648392/800d38a23dc7323d.jpg" img-data="{"format":"jpeg","size":25666,"height":410,"width":774}" class="uploaded-img" style="min-height:200px;min-width:200px;" width="auto" height="auto"/>
</div><p>
</p><blockquote><p>class Solution {
func isPowerOfTwo(_ n: Int) -> Bool {
// 16: 10000
// 15: 01111
return n > 0 && n & (n - 1) == 0
}
}
print(Solution().isPowerOfTwo(16))
</p></blockquote><p>
</p>
网友评论