腾讯面试:比特位计数
生活随笔
收集整理的這篇文章主要介紹了
腾讯面试:比特位计数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
給定一個非負整數num。對于?0 ≤ i ≤ num范圍中的每個數字i,計算其二進制數中的 1 的數目并將它們作為數組返回。
示例 1:
輸入: 2 輸出: [0,1,1]示例 2:
輸入: 5 輸出: [0,1,1,2,1,2]?方法一:Pop count
public class Solution {public int[] countBits(int num) {int[] ans = new int[num + 1];for (int i = 0; i <= num; ++i)ans[i] = popcount(i);return ans;}private int popcount(int x) {int count;for (count = 0; x != 0; ++count)x &= x - 1; //zeroing out the least significant nonzero bitreturn count;} }x &= x - 1??會將x用二進制表示時最右邊的一個1變為0,然后并賦值
方法二:動態規劃 + 最高有效位
public class Solution {public int[] countBits(int num) {int[] ans = new int[num + 1];int i = 0, b = 1;// [0, b) is calculatedwhile (b <= num) {// generate [b, 2b) or [b, num) from [0, b)while(i < b && i + b <= num){ans[i + b] = ans[i] + 1;++i;}i = 0; // reset ib <<= 1; // b = 2b}return ans;} }動態規劃 + 最低有效位
public class Solution {public int[] countBits(int num) {int[] ans = new int[num + 1];for (int i = 1; i <= num; ++i)ans[i] = ans[i >> 1] + (i & 1); // x / 2 is x >> 1 and x % 2 is x & 1return ans;} }觀察規律,最低有效位相當于除以了2
動態規劃 + 最后設置位
public class Solution {public int[] countBits(int num) {int[] ans = new int[num + 1];for (int i = 1; i <= num; ++i)ans[i] = ans[i & (i - 1)] + 1;return ans;} }?
參考地址:https://leetcode-cn.com/problems/counting-bits/solution/bi-te-wei-ji-shu-by-leetcode/
?
總結
以上是生活随笔為你收集整理的腾讯面试:比特位计数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 腾讯面试:打家劫舍 III
- 下一篇: 程序员笑话二十三