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:
    The given integer is guaranteed to fit within the range of a 32-bit signed integer.
    You could assume no leading zero bit in the integer’s binary representation.

    解析:

    给定一个正整数,输出它的补数。补充策略是翻转二进制表示的二进制位。

    给定的整数保证在32位带符号整数的范围内。
    可以在整数的二进制表示中不包含前导零位。
    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.
    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.
    即输出的二进制从给出数字的二进制的最高一个1所在的位数开始取反。

    我的解法:

    public static int getComplement(int n) {
            String binaryN = Integer.toBinaryString(n);
            char[] binaryArray = binaryN.toCharArray();
            StringBuilder sb = new StringBuilder();
            for (char b : binaryArray) {
                sb.append(b == '1' ? 0 : 1);
            }
            return Integer.parseInt(sb.toString(), 2);
        }
    

    效率极其低,类型转换+循环。。

    最优解

    public static int getComplementOptimal(int n) {
            //~运算符是按照当前计算机位数进行计算的
            //如32位,5就是000..0101,32位
            //所以不能直接用~,直接用就是1111..1010
            //需要计算数字最高的1所在位数长度的掩码,即111
            //highestOneBit这个方法获取n二进制表示的最高一位1所代表的数字,
            //如5,0101,最高一位1代表0100 就是4,再-1,就是3,即011
            //因为反正最高一位反过来都是0,所以掩码长度可以为最高一位1的长度少一位
            //所以直接用011作为掩码和~n做与运算,即可得到反码10
            return ~n & (Integer.highestOneBit(n) - 1);
        }
    

    代码只有最后一行,上面是理解注释。。发现Integer是一个神奇的类。。里面有很多不知道的方法。。

  • 相关阅读:
    linux性能测试(转)
    mysql基本操作(数据库,表,字段,记录)
    mysql数据库的简介(安装和卸载)
    mysql数据库
    枚举法
    python数据结构与算法简介
    自学心得
    python 进程线程阅读摘抄
    python并发编程多线程基础1
    python队列
  • 原文地址:https://www.cnblogs.com/shanelau/p/7119093.html
Copyright © 2011-2022 走看看