码迷,mamicode.com
首页 > 其他好文 > 详细

leetcod--Reverse Bits

时间:2015-05-13 22:07:09      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

everse 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?

Related problem: Reverse Integer

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

解题思路:

将一个整形数的二进制序列逆转,后输出二进制序列代表的十进制数

方法一:

采用一个32长度的数组,存储二进制,之后逆转,再计算此数组所表示的整形数。

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        vector<int> a(32,0);
	int mood=0,i=0,temp;
	unsigned int temp1=0;
	while(n/2!=0)
	{
		mood=n%2;
		a[i]=mood;
		n/=2;
		i++;
	}
	a[i]=n%2;
	reverse(a.begin(),a.end());
	for(int j=0;j<32;j++)
	{
		if (a[j]!=0)
		{
			temp=pow(2*1.0,j);
			temp1+=temp;
		}
	}
	return temp1;
    }
};

方法二:

利用位运算符,从低位到高位取出原整形数的各个比特位,对应转换为0~31,1~30,...,31~0。用31-当前下标 就是转换之后的下标,在用左移操作即可实现二进制到十进制的转换。
class Solution {
public:
         uint32_t reverseBits(uint32_t n) {
        uint32_t bin=0;
     for (int i = 0; i < 32; i++) 
     bin+=(n >> i & 1)<<(31-i);
    return bin;
    }
};





leetcod--Reverse Bits

标签:

原文地址:http://blog.csdn.net/sinat_24520925/article/details/45696175

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!