摘要:重復(fù)此步驟直到原數(shù)歸零。注意右移運算符是算術(shù)右移,如果符號位是的話最高位將補,符號位是的話最高位補。當(dāng)原數(shù)不為時,將原數(shù)與上原數(shù)減一的值賦給原數(shù)。因為每次減一再相與實際上是將最左邊的給消去了,所以消去幾次就有幾個。
Number of 1 Bits
移位法 復(fù)雜度Write a function that takes an unsigned integer and returns the number of ’1" bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11" has binary representation 00000000000000000000000000001011, so the function should return 3.
時間 O(1) 空間 O(1)
思路通過與運算符判斷最低位/最高位是否是1,然后再右移/左移。重復(fù)此步驟直到原數(shù)歸零。
注意右移運算符是算術(shù)右移,如果符號位是1的話最高位將補1,符號位是0的話最高位補0。在C/C++中可以先將原數(shù)轉(zhuǎn)換成無符號整數(shù)再處理,而在Java中可以使用無符號右移算術(shù)符>>>。當(dāng)然,左移的解法就沒有這個問題了。
代碼public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int mark = 0b1, count = 0; while(n != 0b0){ if((n & mark)==0b1){ count++; } n = n >>> 1; } return count; } }減一相與法 復(fù)雜度
時間 O(1) 空間 O(1)
思路該方法又叫Brian Kernighan方法。當(dāng)原數(shù)不為0時,將原數(shù)與上原數(shù)減一的值賦給原數(shù)。因為每次減一再相與實際上是將最左邊的1給消去了,所以消去幾次就有幾個1。比如110,減去1得101,相與得100,消去了最左邊的1。
代碼public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int count = 0; while(n != 0b0){ n = n & (n - 1); count++; } return count; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/64427.html
摘要:依次移位復(fù)雜度思路依次移動位數(shù)進行計算。代碼利用性質(zhì)復(fù)雜度,思路代碼 LeetCode[191] Number of 1 Bits Write a function that takes an unsigned integer and returns the number of ’1 bits it has (also known as the Hamming weight). Fo...
Problem Number of 1 BitsWrite a function that takes an unsigned integer and returns the number of ’1 bits it has (also known as the Hamming weight). Example For example, the 32-bit integer 11 has bina...
摘要:題目鏈接題目分析對給定范圍內(nèi)的每個整數(shù),返回其二進制形式下,數(shù)字出現(xiàn)的次數(shù)為質(zhì)數(shù)的次數(shù)。思路由于題目固定了范圍為,次方為千萬。即最多只會出現(xiàn)次。存在則符合題目要求的數(shù)字,否則不計入該數(shù)字。最終代碼若覺得本文章對你有用,歡迎用愛發(fā)電資助。 D57 762. Prime Number of Set Bits in Binary Representation 題目鏈接 762. Prime ...
摘要:題目漢明距離是兩個字符串對應(yīng)位置的不同字符的個數(shù),這里指二進制的不同位置例子我的解法先將,進行異位或運算再轉(zhuǎn)化成二進制然后把去掉算出長度其他方法先算出不同位數(shù),然后用右移運算符算出能右移幾次來獲取距離 1題目 The Hamming distance between two integers is the number of positions at which the corresp...
摘要:思路一比特位移動將比特位逆轉(zhuǎn)過來也就是將十進制數(shù)轉(zhuǎn)化為二進制數(shù),再從右往左獲得每一位上的值,再將這個值添加至結(jié)果值中。根據(jù)分治思想,逆轉(zhuǎn)個比特位等價于分別將每個比特位進行逆轉(zhuǎn)。 題目要求 Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented in...
閱讀 1113·2021-09-22 15:37
閱讀 1138·2021-09-13 10:27
閱讀 2479·2021-08-25 09:38
閱讀 2453·2019-08-26 11:42
閱讀 1535·2019-08-26 11:39
閱讀 1563·2019-08-26 10:58
閱讀 2326·2019-08-26 10:56
閱讀 2575·2019-08-23 18:08