美文网首页Leetcode
Leetcode 476. Number Complement

Leetcode 476. Number Complement

作者: SnailTyan | 来源:发表于2018-09-12 18:56 被阅读2次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Number Complement

    2. Solution

    • Version 1
    class Solution {
    public:
        int findComplement(int num) {
            int result = 0;
            stack<int> s;
            while(num) {
                int bit = num & 1;
                num >>= 1;
                s.push(bit);
            }
            while(!s.empty()) {
                result <<= 1;
                int bit = s.top();
                s.pop();
                result |= (bit ^ 1);
            }
            return result;
        }
    };
    
    • Version 2
    class Solution {
    public:
        int findComplement(int num) {
            int mask = ~0;
            while (num & mask) {
                mask <<= 1;
            }
            return ~mask & ~num;
        }
    };
    

    Reference

    1. https://leetcode.com/problems/number-complement/description/

    相关文章

      网友评论

        本文标题:Leetcode 476. Number Complement

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