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

leetcode——190 Reverse Bits(32位无符号二进制数的翻转)

时间:2015-06-18 09:43:49      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:二进制   leetcode   java   位运算   翻转   

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?

Hide Tags: Bit Manipulation(位操作)


解题思路:

(1)将需要翻转的数n跟1进行“&”运算,取得最低位上的数,

(2)左移到对应位置上,实现翻转。

(3)将翻转的结果加入到result中

(4)将n>>1右移一位,继续遍历


代码如下:

	public static int reverseBits(int n)
	{
		int result=0;
		for (int i = 0; i < 32; i++)
		{
			//获取n对应的二进制数的最右边(最低位)上的数
			int temp=n&1;
			//左移到对应位置上,实现翻转
			int reverseTemp=temp<<(31-i);
			//将翻转的结果加入到result中
			result=result|reverseTemp;
			//进入次低位 >>>:表示无符号数的右移动
			n=n>>>1;
		}
		return result;
	}

leetcode——190 Reverse Bits(32位无符号二进制数的翻转)

标签:二进制   leetcode   java   位运算   翻转   

原文地址:http://blog.csdn.net/zzc8265020/article/details/46539281

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