题目
Reverse bits of a given 32 bits unsigned integer.
Example:
Input: 43261596
Output: 964176192
Explanation: 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?
我的尝试
思路是除以2求出每个数字,然后转为二进制,对二进制进行反转,求出最终结果
感觉不是正确对,因为对字节操作不熟悉,直接看了思路,自己完成代码,完美通过
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
//右移一位,相当于除以2,左移一位相当于乘以2
//数字和1进行&操作,可以获取最后一位数字
int res=0;
for(int i=0;i<32;i++){
res<<=1;
if((n&1)==1) res++;
n>>=1;
}
return res;
}
}
解释一下思路:
1 对于n如何求出每一位数字,十进制的情况是对10求mod,二进制的情况是进行&1操作,结果就是最后一位数字
2 第一步后,对数字n右移动一位,这样重复步骤一就求出当前最后,原来倒数第二对数字,以此类推
3.记得结果,求出的数字是1的加,不是1,不需要记入。很显然这样的结果就是和原来的数字倒序的
汉明权重
leetcode后来又一道类似的题目,题目如下:
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Example 1:
Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011
Example 2:
Input: 128 Output: 1 Explanation: Integer 128 has binary representation 00000000000000000000000010000000
有了上面的逻辑,一次搞定,代码思路一样:
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count=0;
for(int i=0;i<32;i++){
int tmp=(n&1);
if(tmp==1){
count++;
}
n=n>>1;
}
return count;
}
}