LeetCode OJ入门初探-190. 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 as 00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?

Related problem: Reverse Integer

解答:很简单的题目,相当于练习了下如何数字转二进制,二进制转数字的实现,由于取出来的时候就已经是倒叙了,故可以直接计算。


class Solution {
public:
uint32_t reverseBits(uint32_t n) {
char n_bin[32];
for(int i = 0 ; i < 32;i++) { n_bin[i] = n&1; n>>=1;
}
int num = 0;
for(int i = 0;i < 32;i++) { num = 2 * num + n_bin[i] ; } return num; } };

发表评论