for Robot Artificial Inteligence

46. Reverse Bits(어려움)

|

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t m = 0; // 0000000000000000000000000000
        for(int i =0; i<32; i++, n >>=1)
        {
            m<<=1; // 1값이 있을경우 왼쪽으로 쉬프트
            m |= n & 1; // //  
        }
        return m;

    }
};
  • By m«=1, you are left-shifting the value of m by 1 bit in every iteration.
    • If you do m«=1 afterwards, you will get an extra bit 0 on the LSB. since we do it before m =n&1, the extra 0 will show on the left. you can try some tests, the first time of this loop will clearly show it.
  • By m =n&1, i.e., m=m n&1you are checking if the LSB of m or the LSB of n is set, in which case you are setting the LSB of m. Then you move on to the next bit and so on…

Explain

with that in mind lets simplify the loop to 4 bits:

at the beginning m = 0000; n = 1010;

the first iteration m = 0000; n = 0101; n »=1 = n register is shifted to the right by one bit and nothing happens to m;

m«=1 // 현재 m에 1값이 없므로 nothing happen m |= n & 1 // n & 1 =(0101 & 0001)은 0001 // 0000 |= 0001 은 m= 0001이 된다.

second iteration n =0010; // n »=1을 통하여 0101 값을 오른쪽 쉬프트 m= 0010; // 첫번째 iteration에서 m 은 0001이 되었고, m«=1 operation을 통해 1값은 왼쪽으로 옮긴다. m |= n & 1 // n & 1 =(0010 & 0001)은 0000 // 0010 |= 0000 은 m= 0010이 된다.

third iteration m = 0100; n = 0001;

m |= n & 1 // n & 1 =(0001 & 0001)은 0001 // 0100 |= 0001 은 m= 0101이 된다

we return m;

we are essentially pushing bits from 1 register to another.

Comments