本文主要是介绍leetcode338 Counting Bits Java,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Description
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.
解法1
直接调用Integer中的BitCount()方法。
public int[] countBits(int num) {int[] res = new int[num+1];for(int i=0; i<=num; i++) {res[i] = Integer.bitCount(i);}return res;}
解法2
通过res[i] = res[i/2] + (i%2)
public int[] countBits(int num) {int[] res = new int[num+1];for(int i=0; i<=num; i++) res[i] = res[i/2] + (i % 2);return res;}
这篇关于leetcode338 Counting Bits Java的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!