标签:
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?
转换成2进制的string后反转,并且末尾补上原数不足32位的0的个数(乘以2的x次方)。
def reverse_bits(n) 2**(32-n.to_s(2).length)*n.to_s(2).reverse.to_i(2) end
这个方法每次左移一位,末尾增加原来的末位数,循环32次后得到翻转数。
uint32_t reverseBits(uint32_t n) { uint32_t m = 0; for (int i = 0; i< 32 ; i++,n/=2) m = (m<<1) + (n%2); return m; }
标签:
原文地址:http://www.cnblogs.com/lilixu/p/4645496.html