当前位置:网站首页>Algorithm --- bit count (kotlin)
Algorithm --- bit count (kotlin)
2022-07-07 06:52:00 【Xiaomi technology Android research and development caoxinyu】
subject
Bit count
Give you an integer n , about 0 <= i <= n Each of the i , Calculate its binary representation 1 The number of , Returns a length of n + 1 Array of ans As the answer .
Example 1:
Input :n = 2
Output :[0,1,1]
explain :
0 --> 0
1 --> 1
2 --> 10
Example 2:
Input :n = 5
Output :[0,1,1,2,1,2]
explain :
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
Tips :
0 <= n <= 105
https://leetcode.cn/problems/counting-bits/
Solutions
2 Of n The next power There must be only one 1
Because it's all 10000
Whenever more than one 2 Of n The next power
We can put the excess part
Find the result from the previous array
For example, over 2, So the current result is actually 1 + int[2]
resolvent
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
}
summary
1. How to judge a number is 2 Of n The next power ?
x&(x-1) = 0 It means 2 Of n The next power
边栏推荐
- 化工园区危化品企业安全风险智能化管控平台建设四大目标
- 中英文说明书丨ProSci LAG-3 重组蛋白
- Maze games based on JS
- Comment les entreprises gèrent - elles les données? Partager les leçons tirées des quatre aspects de la gouvernance des données
- Config分布式配置中心
- Navicat importing 15g data reports an error [2013 - lost connection to MySQL server during query] [1153: got a packet bigger]
- Abnova 体外转录 mRNA工作流程和加帽方法介绍
- MySQL的主从复制原理
- Performance comparison between Ceres solver and g2o
- 企业如何进行数据治理?分享数据治理4个方面的经验总结
猜你喜欢
ip地址那点事
dolphinscheduler3. X local startup
MYSQL----导入导出&视图&索引&执行计划
Jetpack Compose 远不止是一个UI框架这么简单~
Programmers' daily | daily anecdotes
Matlab tips (29) polynomial fitting plotfit
BindingException 异常(报错)处理
大促过后,销量与流量兼具,是否真的高枕无忧?
MOS tube parameters μ A method of Cox
LM small programmable controller software (based on CoDeSys) Note 23: conversion of relative coordinates of servo motor operation (stepping motor) to absolute coordinates
随机推荐
linux系统rpm方式安装的mysql启动失败
Pinduoduo lost the lawsuit: "bargain for free" infringed the right to know but did not constitute fraud, and was sentenced to pay 400 yuan
什么情况下考虑分库分表
「运维有小邓」符合GDPR的合规要求
js装饰器@decorator学习笔记
毕业设计游戏商城
Matlab tips (29) polynomial fitting plotfit
Postgresql中procedure支持事务语法(实例&分析)
mobx 知识点集合案例(快速入门)
Basic introduction of JWT
Several index utilization of joint index ABC
常用函数detect_image/predict
如何给目标机器人建模并仿真【数学/控制意义】
MYSQL----导入导出&视图&索引&执行计划
【mysqld】Can't create/write to file
RuntimeError: CUDA error: CUBLAS_STATUS_ALLOC_FAILED when calling `cublasCreate(handle)`问题解决
Stack and queue-p78-8 [2011 unified examination true question]
剑指offer-高质量的代码
偏执的非合格公司
Can 7-day zero foundation prove HCIA? Huawei certification system learning path sharing