【LeetCode-面试算法经典-Java实现】【190-Reverse Bits(反转二制)】
【190-Reverse Bits(反转二制)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】代码下载【https://github.com/Wang-Jun-Chao】原题 Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented i
文章共558字 · 阅读需要大约2分钟
一键AI生成摘要,助你高效阅读
问答
·
【190-Reverse Bits(反转二制)】
【LeetCode-面试算法经典-Java实现】【所有题目目录索引】
代码下载【https://github.com/Wang-Jun-Chao】
原题
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?
题目大意
反转一个32位无符号的整数。
解题思路
设这个数为k,用一个初值为0的数r保存反转后的结果,用1对k进行求与,其结果与r进行相加,再对k向右进行一位移位,对r向左进行一位移位。值到k的最后一位处理完。
代码实现
算法实现类
public class Solution {
public int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
result += n & 1;
n >>>= 1;
if (i < 31) {
result <<= 1;
}
}
return result;
}
}
评测结果
点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。
特别说明
欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/47945389】
更多推荐
已为社区贡献4条内容
所有评论(0)