当前位置:网站首页>力扣刷题338.比特位计数
力扣刷题338.比特位计数
2022-06-13 04:19:00 【grt要一直一直努力呀】
思路为:编写一个计算二进制位的函数,然后从0~n依次遍历,得到返回的链表。
Brian Kernighan 算法的原理是:对于任意整数 x,令 x=x & (x−1),该运算将 x 的二进制表示的最后一个 1 变成 0。因此,对 x 重复该操作,直到 x变成 0。
class Solution {
public int[] countBits(int n) {
int[] arr = new int[n+1];
for(int i=0; i<=n; i++){
arr[i] = countOne(i);
}
return arr;
}
public int countOne(int x){
int res = 0;
while(x>0){
x=x&(x-1);
res++;
}
return res;
}
}
边栏推荐
- MCU: pcf8591 hardware interface
- Dumi builds a document blog
- [test development] basic concepts related to testing
- Use ASE encryption and decryption cache encapsulation in Vue project
- 120. triangle minimum path sum - Dynamic Planning
- [Yugong series] June 2022 Net architecture class 080 master cluster and database switching of distributed middleware schedulemaster
- MVP framework for personal summary
- Catalan number
- 个人总结的MVP框架
- LVS four layer load balancing cluster (3) cluster function classification - HPC
猜你喜欢
EMC rectification outline
小程序基础入门(黑马学习笔记)
Single chip microcomputer: infrared remote control communication principle
重读经典:《End-to-End Object Detection with Transformers》
MCU: NEC protocol infrared remote controller
Value of line height
干预分析 + 伪回归
Solution to failure to download files by wechat scanning QR code
Lightweight digital mall system based on PHP
Simple static web page + animation (small case)
随机推荐
PAT 1054 The Dominant Color
Dagger2学习之Module的应用(二)
【剑指Offer】面试题25.合并两个有序的链表
Lambda termination operation Max & min
Single chip microcomputer: infrared remote control communication principle
Unity shader learning 004 shader debugging platform difference third-party debugging tools
Single chip microcomputer: pcf8591 application program
Redis hyperloglog cardinality statistics algorithm
史上最详细的Swin-Transformer 掩码机制(mask of window attentation)————shaoshuai
ET框架-22 创建ServerInfo实体及事件
2019 Blue Bridge Cup
[zeloengine] localization process /imgui Chinese culture
LVS four layer load balancing cluster (3) cluster function classification - HPC
Redis-HyperLogLog-基数统计算法
Et framework -22 creating serverinfo entities and events
Redis数据持久化
Intervention analysis + pseudo regression
干预分析 + 伪回归
Advanced Mathematics (Seventh Edition) Tongji University exercises 1-2 personal solutions
Manage PC startup items