本文主要是介绍LeetCode 338 Counting Bits (递推),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
Example:
For num = 5
you should return [0,1,1,2,1,2]
.
Follow up:
- It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
- Space complexity should be O(n).
- Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
题目链接:https://leetcode.com/problems/counting-bits/
题目分析:直接递推即可,若当前数字是奇数,其二进制中1的个数相当于它右移一位的那个数中1的个数加1,偶数则不加1
public class Solution {public int[] countBits(int num) {int[] dp = new int[num + 1];Arrays.fill(dp, 0);dp[0] = 0;for(int i = 1; i <= num; i ++) {dp[i] += dp[i >> 1] + (i & 1);}return dp;}
}
这篇关于LeetCode 338 Counting Bits (递推)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!