LeetCode刷題EASY篇Reverse Bits
阿新 • • 發佈:2018-12-13
題目
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;
}
}