当前位置:网站首页>算法---比特位计数(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次幂
边栏推荐
- 反射(二)
- Developers don't miss it! Oar hacker marathon phase III chain oar track registration opens
- Markdown displays pictures side by side
- Postgresql中procedure支持事务语法(实例&分析)
- 面试中有哪些经典的数据库问题?
- c面试 加密程序:由键盘输入明文,通过加密程序转换成密文并输出到屏幕上。
- Symmetric binary tree [tree traversal]
- 雷特智能家居龙海祁:从专业调光到全宅智能,20年专注成就专业
- Stack and queue-p78-8 [2011 unified examination true question]
- 程序员的日常 | 每日趣闻
猜你喜欢

JWT certification

学习笔记|数据小白使用DataEase制作数据大屏

The difference between string constants and string objects when allocating memory

Haqi projection Black Horse posture, avec seulement six mois de forte pénétration du marché des projecteurs de 1000 yuans!

Redis(二)—Redis通用命令

BindingException 异常(报错)处理

学术报告系列(六) - Autonomous Driving on the journey to full autonomy

精准时空行程流调系统—基于UWB超高精度定位系统

Abnova 体外转录 mRNA工作流程和加帽方法介绍

网络基础 —— 报头、封装和解包
随机推荐
MySQL卸载文档-Windows版
怎样查找某个外文期刊的文献?
string(讲解)
企业如何进行数据治理?分享数据治理4个方面的经验总结
面试中有哪些经典的数据库问题?
Crudini profile editing tool
Performance comparison between Ceres solver and g2o
C language sorting (to be updated)
[start from scratch] detailed process of deploying yolov5 in win10 system (CPU, no GPU)
【从零开始】win10系统部署Yolov5详细过程(CPU,无GPU)
Which foreign language periodicals are famous in geology?
Several key steps of software testing, you need to know
Navicat importing 15g data reports an error [2013 - lost connection to MySQL server during query] [1153: got a packet bigger]
一条慢SQL拖死整个系统
ip地址那点事
Abnova 体外转录 mRNA工作流程和加帽方法介绍
c语言(结构体)定义一个User结构体,含以下字段:
项目实战 五 拟合直线 获得中线
博士申请 | 上海交通大学自然科学研究院洪亮教授招收深度学习方向博士生
Linear algebra (1)