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

leetcode_190题——Reverse Bits(bitset的使用)

时间:2015-05-01 16:01:45      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

Reverse Bits

 Total Accepted: 18472 Total Submissions: 66483My Submissions

 

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?

Related problem: Reverse Integer

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

 

Hide Tags
 Bit Manipulation
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

     这道题目的意思是将一个32位字节存储的一个数,在二进制上前后旋转,然后得到一个新的二进制数,再将二进制数转换成unsigned long型的数输出

所以这道题用C++做的话很简单,主要是考虑bitset的使用(初始化和使用函数to_ulong)

#include<iostream>
#include <bitset>
using namespace std;
typedef unsigned long uint32_t;


uint32_t reverseBits(uint32_t n) {
	uint32_t result;
	//unsigned long val=n;
	int val=n;
	bitset<32>bit_temp(val);

	for(int i=0;i<16;i++)
	{
		bool temp;
		temp=bit_temp[i];
		bit_temp[i]=bit_temp[31-i];
		bit_temp[31-i]=temp;
	}
	result=bit_temp.to_ulong();
	return result;
}

int main()
{
	//cout<<reverseBits(1)<<endl;
	
	unsigned long a=12;

	cout<<sizeof(unsigned long)<<endl;
	cout<<sizeof(int)<<endl;
	cout<<sizeof(long)<<endl;
	bitset<32> temp(a);

}

  

leetcode_190题——Reverse Bits(bitset的使用)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4470739.html

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