Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

231. 2 的幂 #43

Open
webVueBlog opened this issue Aug 31, 2022 · 0 comments
Open

231. 2 的幂 #43

webVueBlog opened this issue Aug 31, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

231. 2 的幂

Description

Difficulty: 简单

Related Topics: 位运算, 递归, 数学

给你一个整数 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

**进阶:**你能够不使用循环/递归解决此问题吗?

Solution

Language: JavaScript

/**
 * @param {number} n
 * @return {boolean}
 */
// 二进制表示
// var isPowerOfTwo = function(n) {
//     return n > 0 && (n & (n - 1)) === 0
// };

// var isPowerOfTwo = function(n) {
//     return n > 0 && (n & -n) === n
// };


var isPowerOfTwo = function(n) {
    if (n <= 0) return false
    return (n & (n-1)) === 0
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant