日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

腾讯面试:比特位计数

發(fā)布時間:2025/6/15 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 腾讯面试:比特位计数 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

題目描述

給定一個非負整數(shù)num。對于?0 ≤ i ≤ num范圍中的每個數(shù)字i,計算其二進制數(shù)中的 1 的數(shù)目并將它們作為數(shù)組返回。

示例 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變?yōu)?,然后并賦值

方法二:動態(tài)規(guī)劃 + 最高有效位

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;} }

動態(tài)規(guī)劃 + 最低有效位

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;} }

觀察規(guī)律,最低有效位相當(dāng)于除以了2

動態(tài)規(guī)劃 + 最后設(shè)置位

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/
?

總結(jié)

以上是生活随笔為你收集整理的腾讯面试:比特位计数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。