9ms, C++ solution


  • 1
    S
        class Solution {
        public:
            uint32_t reverseBits(uint32_t n) {
                uint32_t res=0;
                for(int i=0; i<32; i++){
                    res += (n>>i & 1) * (1 << (31-i));
                }
                return res;
            }
    
    };

  • 0
    L

    Can you explain it?


  • 0
    C

    His idea is something like this:
    int n = 123;
    int res = 0;
    for (int i = 0; i < 3; ++i)
    {
    res += (n % 10) * pow(10, 2-i);
    n /= 10;
    }
    He gets every single bit and multiply it with its weight in the reversed integer.(I hope I've made myself understood.)


  • 0
    L

    So clear. Thank you so much!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.