当前位置:网站首页>算法---比特位计数(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次幂
边栏推荐
- MySQL卸载文档-Windows版
- Stack and queue-p79-10 [2014 unified examination real question]
- Stack and queue-p79-9
- c语言面试写一个函数在字符串N中查找第一次出现子串M的位置。
- 反射(二)
- 软件测试到了35岁,真的就干不动了吗?
- leetcode 509. Fibonacci Number(斐波那契数字)
- 2022 Android interview essential knowledge points, a comprehensive summary
- MySQL (x)
- "Parse" focalloss to solve the problem of data imbalance
猜你喜欢

Redis(一)——初识Redis

Redis (II) - redis General Command

直击2022ECDC萤石云开发者大会:携手千百行业加速智能升级

Jmeter 5.5版本发布说明

ESXI挂载移动(机械)硬盘详细教程

Installing redis and windows extension method under win system

A program lets you understand what static inner classes, local inner classes, and anonymous inner classes are

偏执的非合格公司

Shared memory for interprocess communication

如何给目标机器人建模并仿真【数学/控制意义】
随机推荐
ETCD数据库源码分析——从raftNode的start函数说起
"Parse" focalloss to solve the problem of data imbalance
Google Chrome browser released patch 103.0.5060.114 to fix the 0-day vulnerability
快速定量,Abbkine 蛋白质定量试剂盒BCA法来了!
matlab / ENVI 主成分分析实现及结果分析
Ant manor safety helmet 7.8 ant manor answer
面试中有哪些经典的数据库问题?
项目实战 五 拟合直线 获得中线
leetcode 509. Fibonacci Number(斐波那契数字)
Shared memory for interprocess communication
C interview encryption program: input plaintext by keyboard, convert it into ciphertext through encryption program and output it to the screen.
Force deduction 62 different paths (the number of all paths from the upper left to the lower right of the matrix) (dynamic planning)
POI导出Excel:设置字体、颜色、行高自适应、列宽自适应、锁住单元格、合并单元格...
Pinduoduo lost the lawsuit: "bargain for free" infringed the right to know but did not constitute fraud, and was sentenced to pay 400 yuan
Abnova 膜蛋白脂蛋白体技术及类别展示
FPGA课程:JESD204B的应用场景(干货分享)
Matlab / envi principal component analysis implementation and result analysis
Stack and queue-p78-8 [2011 unified examination true question]
How can I check the DOI number of a foreign document?
C语言面试 写一个函数查找两个字符串中的第一个公共字符串