zoukankan      html  css  js  c++  java
  • LeetCode. 476. Number Complement

    Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

    Note:

    1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
    2. You could assume no leading zero bit in the integer’s binary representation.

    Example 1:

    Input: 5
    Output: 2
    Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

    Example 2:

    Input: 1
    Output: 0
    Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

    分析:

    给定一个正整数,按位取反, 比如题目中给出的5,二进制为101,那么取反就是010, 010对应的十进制数是2.

    实现这个功能的话,按位取反,很容易想到异或操作符^, 将原数比如101与111进行抑或操作,那么所得结果就是010.也就是我们需要的。

    代码实现:

    function complement(number) {
        var mask = 1;
        var temp = number;
        while( temp > 0) {
            temp = temp >> 1;
            mask = mask << 1;
        }
        return number ^ (mask-1);
    }
    complement(1);

    这里 mask-1是为了取111...值。

  • 相关阅读:
    latex插入图片
    装virtualenv和flask
    GitHub Pages写博客
    用模拟退火算法进行特征选择
    用遗传算法进行特征选择
    智能垃圾桶
    蚁群算法 与 A*算法 寻找最优路径 对比 (pygame)
    pygame
    pyinstaller打包python应用程序
    内网渗透之信息收集-linux
  • 原文地址:https://www.cnblogs.com/gogolee/p/6644762.html
Copyright © 2011-2022 走看看