My 14ms C++ code


  • 2
    G

    Here is my code:

    class Solution {
    public:
        uint32_t reverseBits(uint32_t n) {
            uint32_t result = 0;
            int times = 32;
            while (times > 0) {
                result += n & 1;
                if (times == 1)
                    break;
                n = n >> 1;
                result = result << 1;
                times--;
            }
            return result;
        }
    };

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

  • 0
    E

    My solution runs for only 3 ms .

    It is similar to yours.

    uint32_t reverseBits(uint32_t n) {
      uint32_t m = 0;
      for(int i=0;i<31;++i){
          m |= (n & 1);
          m = m<<1;
          n = n>>1;
      }
      m |= (n & 1);
      return m;
    }

  • 0
    W

    res |= (n >> i & 1) << (31 - i); same as you


Log in to reply
 

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