题目:
Reverse bits of a given 32 bits unsigned integer
反转给定32位无符号整数的位
Input: 00000010100101000001111010011100 Output: 00111001011110000010100101000000 Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000. Input: 11111111111111111111111111111101 Output: 10111111111111111111111111111111 Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10101111110010110010011101101001. Note: · Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned. · In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above the input represents the signed integer -3 and the output represents the signed integer -1073741825
方法:
由于此处输入的是无符号数字,并且已知位数,所以可以直接用循环来进行操作(使用for循环而不是使用是否n=0来判断跳出是因为:负数右移后左边自动补1,不会等于0)
对于数字00011111111011111101111001111101来说,我们从右到左来得到该位是1还是0,并根据情况对返回的re进行操作
具体为:
初始化re=0
使用mask=1来得到当前n的最右位是0还是1——mask&n ==1则当前最右位是1,否则为0
如果当前最右位是1,则将re+1,并将re左移一位;否则将re左移1位
将n右移一位
【注意】由于for循环从0到31,则每次循环在re中更新当前位数,如果在每次循环的最后对re进行左移,则在第31位数保存后,会再次左移后再经过判断跳出循环,会导致一个数的丢失,所以此处将re的左移放在了每次循环的最开始(最开始0左移依旧得0,不影响结果)
代码:
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int re = 0;
int mask = 1;
for(int i=0;i<32;i++){
re = re<<1;
if((n&mask)==1){
re = re+1;
}
n = n>>1;;
}
return re;
}
}