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...值。

  • 相关阅读:
    RabbitMQ知识梳理
    feign.FeignException: status 400 reading
    rabbitmq监控之消息确认ack
    Docker 安装redis mysql rabbitmq
    linux搭建GitLab
    杀死服务进程并重新启动,同时监听日志打印
    MySQL数据库连接报错
    idea: unable to import maven project
    线程池ThreadPool实战
    【2-SAT】URAL
  • 原文地址:https://www.cnblogs.com/gogolee/p/6644762.html
Copyright © 2011-2022 走看看