--- title: 'LeetCode 190. Reverse Bits' disqus: hackmd --- # LeetCode 190. Reverse Bits ## Description Reverse bits of a given 32 bits unsigned integer. Note: Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. ## Example Input: n = 00000010100101000001111010011100 Output: 964176192 (00111001011110000010100101000000) Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000. ## Constraints The input must be a binary string of length 32 ## Answer 此題可藉由bit操作將高位元的bit和低位元的bit區分出來,然後位置互換即可。從16位、8位、4位、2位、1位依序交換。 ```Cin= uint32_t reverseBits(uint32_t n) { if(n == 0){return 0;} n = ((n & 0xFFFF0000) >> 16) | ((n & 0x0000FFFF) << 16); n = ((n & 0xFF00FF00) >> 8 ) | ((n & 0x00FF00FF) << 8 ); n = ((n & 0xF0F0F0F0) >> 4 ) | ((n & 0x0F0F0F0F) << 4 ); n = ((n & 0xcccccccc) >> 2 ) | ((n & 0x33333333) << 2 ); n = ((n & 0xaaaaaaaa) >> 1 ) | ((n & 0x55555555) << 1 ); return n; } ``` 或是用loop依序將0~31 bit的情況取出,若為1就給定,若不為1就往下推進。 ```Cin= uint32_t reverseBits(uint32_t n){ if(n == 0){return 0;} int i = 0; uint32_t ans = 0; for(i = 0; i<32; i++){ ans<<=1; if(n&1){ans|=1;} n>>=1; } return ans; } ``` ## Link https://leetcode.com/problems/reverse-bits/ ###### tags: `Leetcode`