• [LeetCode] 231. Power of Two


    Given an integer n, return true if it is a power of two. Otherwise, return false.

    An integer n is a power of two, if there exists an integer x such that n == 2x.

    Example 1:

    Input: n = 1
    Output: true
    Explanation: 20 = 1
    

    Example 2:

    Input: n = 16
    Output: true
    Explanation: 24 = 16
    

    Example 3:

    Input: n = 3
    Output: false
    

    Example 4:

    Input: n = 4
    Output: true
    

    Example 5:

    Input: n = 5
    Output: false

    Constraints:

    • -231 <= n <= 231 - 1

    Follow up: Could you solve it without loops/recursion?

    2 的幂。

    给你一个整数 n,请你判断该整数是否是 2 的幂次方。如果是,返回 true ;否则,返回 false 。

    如果存在一个整数 x 使得 n == 2x ,则认为 n 是 2 的幂次方。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/power-of-two
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    这里我提供一种位运算的做法,如果你对位运算很敏感,你会发现,所有2的某次方的数字,转化成二进制之后,都只有一个 1。比如 2->0010, 4->0100, 8->1000......

    所以思路是比较 n & n-1 是否等于 0 即可。因为如果 n 是 2 的某次方,比它小 1 的数字里面一定是一堆 1。

    举个例子,16的二进制是10000,15的二进制是01111,两者做AND运算得到0。代码如下,

    JavaScript实现

    1 /**
    2  * @param {number} n
    3  * @return {boolean}
    4  */
    5 var isPowerOfTwo = function (n) {
    6     return n > 0 && (n & (n - 1)) === 0;
    7 };

    Java实现

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

    LeetCode 题目总结

  • 相关阅读:
    linux 查看安装软件位置(持续跟新)
    POJ 3661 Running (DP思想)
    stringstream的用法
    关于实验室搬家
    POJ 搜索(2)
    Treap的插入删除实现
    碰到一道不错的扩展欧几里德题目 whu 1338
    SRM 144
    关于无向图双连通问题
    POJ 动态规划(2)
  • 原文地址:https://www.cnblogs.com/cnoodle/p/11675164.html
Copyright © 2020-2023  润新知