內(nèi)容
編寫一個函數(shù)访诱,輸入是一個無符號整數(shù)瘾境,返回其二進制表達式中數(shù)字位數(shù)為 ‘1’ 的個數(shù)(也被稱為漢明重量)崔梗。
示例 :
<pre style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 13px; display: block; padding: 9.5px; margin: 0px 0px 10px; line-height: 1.42857; color: rgb(51, 51, 51); word-break: break-all; word-wrap: break-word; background-color: rgb(245, 245, 245); border: 1px solid rgb(204, 204, 204); border-radius: 4px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">輸入: 11
輸出: 3
解釋: 整數(shù) 11 的二進制表示為 **00000000000000000000000000001011**
</pre>
示例 2:
<pre style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 13px; display: block; padding: 9.5px; margin: 0px 0px 10px; line-height: 1.42857; color: rgb(51, 51, 51); word-break: break-all; word-wrap: break-word; background-color: rgb(245, 245, 245); border: 1px solid rgb(204, 204, 204); border-radius: 4px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">輸入: 128
輸出: 1
解釋: 整數(shù) 128 的二進制表示為 00000000000000000000000010000000</pre>
思路
代碼
/**
* @param {number} n - a positive integer
* @return {number}
*/
var hammingWeight = function(n) {
n=n.toString(2);
var count=0;
for(var i of n){
if(i=='1'){
count++
}
}
return count
};