zoukankan      html  css  js  c++  java
  • 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.

    链接:https://leetcode.com/problems/number-complement/#/description

    3/28/2017

    做完一遍要立即差错。

     1 public class Solution {
     2     public int findComplement(int num) {
     3         int tmp = num ^ 0xffffffff;
     4         int reset = 0x80000000;
     5         for (int i = 0; i < 32; i++) {
     6             if ((tmp & reset) != 0) {
     7                 tmp &= (reset ^ 0xffffffff);
     8                 reset >>= 1;
     9             }
    10             else break;
    11         }
    12         return tmp;
    13     }
    14 }

    别人的好算法,右半部分是mask,把最右边的位置1。看来要系统研究一下Java本身的一些方法,比如Integer的很多跟bit有关的方法

    1 public class Solution {
    2     public int findComplement(int num) {
    3         return ~num & ((Integer.highestOneBit(num) << 1) - 1);
    4     }
    5 }

    C++,mask右边补0,最后取反也跟前面的mask一样了

    1 class Solution {
    2 public:
    3     int findComplement(int num) {
    4         unsigned mask = ~0;
    5         while (num & mask) mask <<= 1;
    6         return ~mask & ~num;
    7     }
    8 };

    这个方法也很有意思,是将从最高的为1的位开始,所有右边的位数置为1,每次重复都是2倍的长度。原因?最左边位是1,右移之后原来此左边位也变成了1,第二次时候把最高的2位都用来置右边2位。直到最后一步为总位数的一半

    1 int findComplement(int num) {
    2     int mask = num;
    3     mask |= mask >> 1;
    4     mask |= mask >> 2;
    5     mask |= mask >> 4;
    6     mask |= mask >> 8;
    7     mask |= mask >> 16;
    8     return num ^ mask;
    9 }

    更多讨论:https://discuss.leetcode.com/category/608/number-complement

  • 相关阅读:
    string.Format组合跳转路径
    jquery 设置asp:dropdownlist 选中项
    asp:UpdatePanel中js失效问题已解决
    repeater 一个td多个div显示图片
    aps.net js获取服务器控件
    nfs—文件转换器
    Linux之文件权限
    关于Linux与Windows的在服务器的一些区别
    关于Linux目录结构的理解
    新的旅程
  • 原文地址:https://www.cnblogs.com/panini/p/6637829.html
Copyright © 2011-2022 走看看