"100 Lectures on Algorithm Zero Basics" (Lesson 48) Bit Operation (Left Shift)

content

left shift operation

190. Reversing Bits

231. Powers of 2

476. Number's Complement

338. Bit Count


left shift operation


The left shift operation, as the name implies, is to shift its binary representation to the left by one bit, and the lower bit is filled with 0. Because of the meaning of each digit in binary in decimal, the left shift operation is equivalent {\color{DarkGreen} *2^n}. For the problem of overflow , the left shift operation will also directly ignore this problem, and the high-order overflow can be thrown away directly ( natural overflow ).



190. Reversing Bits

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t ans=0;
        for(int i=0;i<32;i++) {
            ans=(ans<<1)|(n&1);
            n>>=1;
        }
        return ans;
    }
};

231. Powers of 2

class Solution {
public:
    bool isPowerOfTwo(int n) {
        for(int i=0;i<31;i++) {
            if((1<<i)==n) return true;
        }
        return false;
    }
};

476. Number's Complement

class Solution {
public:
    int findComplement(int num) {
        int ans=0,cnt=0;
        while(num) {
            int t=num&1;
            if(!t) ans|=1<<cnt;
            cnt++;
            num>>=1;
        }
        return ans;
    }
};

338. Bit Count

class Solution {
public:
    vector<int> countBits(int n) {
        vector<int>res;
        for(int i=0;i<=n;i++) {
            int j=i,cnt=0;
            while(j) {
                if(j&1) cnt++;
                j>>=1;
            }
            res.push_back(cnt);
        }
        return res;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324030096&siteId=291194637