問題:
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?
大意:
翻轉(zhuǎn)32位無符號(hào)整型數(shù)。
比如給出輸入為 43261596 (二進(jìn)制表示為 00000010100101000001111010011100),返回 964176192 (二進(jìn)制表示為 00111001011110000010100101000000)。
進(jìn)階:
如果這個(gè)函數(shù)被頻繁調(diào)用,你怎么優(yōu)化它?
思路:
一開始用笨辦法先一位位轉(zhuǎn)化成代表二進(jìn)制數(shù)的數(shù)組然后重新計(jì)算出結(jié)果,但是題目給出的是32位無符號(hào)數(shù),也就是說大于int型的范圍了,很麻煩。
后來看了看發(fā)現(xiàn)根本不需要這么麻煩,直接進(jìn)行位移運(yùn)算,因?yàn)槭且D(zhuǎn)過來,所以一邊向右位移輸入的數(shù)字,一邊根據(jù)右移后原數(shù)字跟1的與操作結(jié)果來將結(jié)果數(shù)字左移,最后直接返回就完了,完全不需要轉(zhuǎn)成二進(jìn)制又轉(zhuǎn)回來,都是一樣的。
不過這里要注意右移時(shí)要使用無符號(hào)右移。
他山之石:
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
result += n & 1;
n >>>= 1; // 必須進(jìn)行無符號(hào)位移
if (i < 31) // 最后一次不需要進(jìn)行位移
result <<= 1;
}
return result;
}
}
合集:https://github.com/Cloudox/LeetCode-Record