编写测试用例的时候,要特别注意需要使用 bindex 进行二进制数到十进制数的转换
<?php
// php进制转换 https://www.jianshu.com/p/9451a2641e14
// 十进制->二进制 decbin
// 十进制->二进制 decoct
// 十进制->十六进制 dechex
// 总结: 二进制: bin, 8进制: oct, 十进制:dec, 十六进制: hex
class Solution {
/**
* @param int $n
* @return int
*/
function hammingWeight($n) {
$ret = 0;
for($i = 0; $i < 32; $i++) {
$bitRes = $n & (1 << $i);
if($bitRes != 0) {
$ret++;
}
}
return $ret;
}
}
$s = new Solution();
$ans = $s->hammingWeight(bindec('00000000000000000000000000001011'));
assert($ans == 3, '00000000000000000000000000001011 result should be 3');
$ans = $s->hammingWeight(bindec('00000000000000000000000010000000'));
assert($ans == 1, '00000000000000000000000010000000 result should be 1');
$ans = $s->hammingWeight(bindec('11111111111111111111111111111101'));
assert($ans == 31, '11111111111111111111111111111101 result should be 31');