美文网首页
Number Complement

Number Complement

作者: casuality4windy | 来源:发表于2017-09-04 09:53 被阅读0次
    Problem

    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.

    Example

    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.

    Solution1 (My Solution)
    class Solution {
    public:
        int findComplement(int num) {
            std::bitset<32> bits(num);
            int endPos = ignoreLeadingZero(bits);
            for (int i = 0; i <= endPos; i++){
                 bits[i] = !bits[i];    
            }
            
            return int(bits.to_ulong());
        }
        
    private:
        int ignoreLeadingZero(bitset<32>& bits){
            size_t bitsLength = bits.size();
            for (int i = bitsLength - 1; i >= 0; i--){
                if (bits[i] == 0) continue;
                else return i;
            }
        }
    };
    
    Solution2
    class Solution {
    public:
        int findComplement(int num) {
            unsigned mask = ~0;
            while (num & mask) mask <<= 1;
            return ~mask & ~num;
        }
    };
    
    • Solution2 通过求其掩码的方式,基于二进制运算,速度较快。

    相关文章

      网友评论

          本文标题:Number Complement

          本文链接:https://www.haomeiwen.com/subject/rwisjxtx.html