[LeetCode] Reverse Bits
Reverse Bits
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up: If this function is called many times, how would you optimize it?
問題解決の考え方:
シフトで計算します.コードは次のとおりです.
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up: If this function is called many times, how would you optimize it?
問題解決の考え方:
シフトで計算します.コードは次のとおりです.
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t result=0;
int size = sizeof(uint32_t)*8;
for(int i=0; i<size; i++){
result = result << 1;
result += n%2;
n=n>>1;
}
return result;
}
};
は、nが小さな数であれば、sizeビットをループする必要はなく、nが右にシフトして0になると、ループから飛び出すことができることに気づいた.result残りの桁数を左に移動すればいいです.次に、最適化されたコードを示します.class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t result=0;
int size = sizeof(uint32_t)*8;
int i=0; //
while(n!=0){
result = result << 1;
result += n%2;
n=n>>1;
i++;
}
result <<= size - i;
return result;
}
};