当前位置:网站首页>算法---比特位计数(Kotlin)
算法---比特位计数(Kotlin)
2022-07-07 02:27:00 【小米科技Android 研发曹新雨】
题目
比特位计数
给你一个整数 n ,对于 0 <= i <= n 中的每个 i ,计算其二进制表示中 1 的个数 ,返回一个长度为 n + 1 的数组 ans 作为答案。
示例 1:
输入:n = 2
输出:[0,1,1]
解释:
0 --> 0
1 --> 1
2 --> 10
示例 2:
输入:n = 5
输出:[0,1,1,2,1,2]
解释:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
提示:
0 <= n <= 105
https://leetcode.cn/problems/counting-bits/
解决思路
2的n次幂 一定是只有一个1
因为都是10000
每当超过一个2的n次幂
我们就可以把超过的部分
从之前的数组里面找出结果
比如超过2,那么当前的结果其实就是1 + int[2]
解决方法
fun countBits(n: Int): IntArray {
val intArray = IntArray(n + 1)
var highBit = 0
for (i in 1..n) {
if ((i and (i - 1)) == 0) {
intArray[i] = 1
highBit = i
} else {
intArray[i] = intArray[i - highBit] + 1
}
}
return intArray
}
总结
1.怎么判断一个数是2的n次幂?
x&(x-1) = 0 就说明是2的n次幂
边栏推荐
- Performance comparison between Ceres solver and g2o
- JVM in-depth
- Navicat importing 15g data reports an error [2013 - lost connection to MySQL server during query] [1153: got a packet bigger]
- JWT 认证
- Open the blue screen after VMware installation
- 项目实战 五 拟合直线 获得中线
- 【从零开始】win10系统部署Yolov5详细过程(CPU,无GPU)
- 隐马尔科夫模型(HMM)学习笔记
- 雷特智能家居龙海祁:从专业调光到全宅智能,20年专注成就专业
- [start from scratch] detailed process of deploying yolov5 in win10 system (CPU, no GPU)
猜你喜欢
反射(二)
【OpenCV】形态学滤波(2):开运算、形态学梯度、顶帽、黑帽
MySQL installation
LM小型可编程控制器软件(基于CoDeSys)笔记二十三:伺服电机运行(步进电机)相对坐标转换为绝对坐标
ETCD数据库源码分析——从raftNode的start函数说起
How can I check the DOI number of a foreign document?
屏幕程序用串口无法调试情况
Programmers' daily | daily anecdotes
Common problems of caching in high concurrency scenarios
Shared memory for interprocess communication
随机推荐
A program lets you understand what static inner classes, local inner classes, and anonymous inner classes are
Abnova 膜蛋白脂蛋白体技术及类别展示
How to find the literature of a foreign language journal?
Etcd database source code analysis -- starting from the start function of raftnode
Ant manor safety helmet 7.8 ant manor answer
企业如何进行数据治理?分享数据治理4个方面的经验总结
港科大&MSRA新研究:关于图像到图像转换,Fine-tuning is all you need
Prompt for channel security on the super-v / device defender side when installing vmmare
一条慢SQL拖死整个系统
ICML 2022 | 探索语言模型的最佳架构和训练方法
Postgresql源码(60)事务系统总结
中英文说明书丨ProSci LAG-3 重组蛋白
PostgreSQL database timescaledb function time_ bucket_ Gapfill() error resolution and license replacement
Stack and queue-p79-9
tkinter窗口选择pcd文件并显示点云(open3d)
What are the classic database questions in the interview?
ESXI挂载移动(机械)硬盘详细教程
Postgresql源码(59)分析事务ID分配、溢出判断方法
缓存在高并发场景下的常见问题
impdp的transform参数的测试