当前位置:网站首页>算法---比特位计数(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次幂
边栏推荐
- Stack and queue-p79-10 [2014 unified examination real question]
- 学术报告系列(六) - Autonomous Driving on the journey to full autonomy
- 哈趣投影黑馬之姿,僅用半年强勢突圍千元投影儀市場!
- Stack and queue-p79-9
- Matlab / envi principal component analysis implementation and result analysis
- MySQL的安装
- c语言(结构体)定义一个User结构体,含以下字段:
- Abnova 体外转录 mRNA工作流程和加帽方法介绍
- Postgresql中procedure支持事务语法(实例&分析)
- POI export to excel: set font, color, row height adaptation, column width adaptation, lock cells, merge cells
猜你喜欢
Apache ab 压力测试
What are the classic database questions in the interview?
Pinduoduo lost the lawsuit: "bargain for free" infringed the right to know but did not constitute fraud, and was sentenced to pay 400 yuan
ESXI挂载移动(机械)硬盘详细教程
2022 Android interview essential knowledge points, a comprehensive summary
拼多多败诉:“砍价免费拿”侵犯知情权但不构成欺诈,被判赔400元
SVN version management in use replacement release and connection reset
面试中有哪些经典的数据库问题?
Ha Qu projection dark horse posture, only half a year to break through the 1000 yuan projector market!
Unable to debug screen program with serial port
随机推荐
mobx 知识点集合案例(快速入门)
Google Chrome browser released patch 103.0.5060.114 to fix the 0-day vulnerability
impdp的transform参数的测试
拼多多败诉:“砍价免费拿”侵犯知情权但不构成欺诈,被判赔400元
RuntimeError: CUDA error: CUBLAS_STATUS_ALLOC_FAILED when calling `cublasCreate(handle)`问题解决
化工园区危化品企业安全风险智能化管控平台建设四大目标
Abnova 体外转录 mRNA工作流程和加帽方法介绍
JESD204B时钟网络
基本Dos命令
直击2022ECDC萤石云开发者大会:携手千百行业加速智能升级
[SOC FPGA] peripheral PIO button lights up
ViewModelProvider.of 过时方法解决
Common problems of caching in high concurrency scenarios
Array proof during st table preprocessing
FlexRay通信协议概述
HKUST & MsrA new research: on image to image conversion, fine tuning is all you need
ESXI挂载移动(机械)硬盘详细教程
Unable to debug screen program with serial port
ceres-solver和g2o性能比较
Redis(二)—Redis通用命令