leetcode每日一题之6. 比特位计数

比特位计数

解法1

首先,根据可以很轻松的想到可以循环number,然后找对应的number二进制数中的1的数量。代码如下

class Solution {

    /**
     * @param Integer $num
     * @return Integer[]
     */
    function countBits($num) {
        $counts = [];
        for($j = 0; $j <= $num; $j++){
            $string = base_convert($j, 10, 2); 
            $count = 0; 
            for($i = 0; $i < strlen($string); $i++){
                if($string[$i] == 1) $count++;
            }
            $counts[] = $count;
        }
        return $counts;
    }
}

解法2:动态规划

可以总结规律,当为偶数时,number中1的数量和number/2中的1的数量是一致的。当为奇数时,number中1的数量等于number - 1 中1的数量 + 1.代码如下

class Solution {

    /**
     * @param Integer $num
     * @return Integer[]
     */
    function countBits($num) {
        $counts = [0];
        for($j = 1; $j <= $num; $j++){  
            $counts[$j] = $counts[$j >> 1] + ($j & 1);
        }
        return $counts;
    }
}
原文地址:https://www.cnblogs.com/qiye5757/p/14476383.html