当前位置:网站首页>338. Counting Bits
338. Counting Bits
2022-06-22 13:15:00 【Sterben_ Da】
338. Counting Bits
Easy
7064333Add to ListShare
Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.
Example 1:
Input: n = 2 Output: [0,1,1] Explanation: 0 --> 0 1 --> 1 2 --> 10
Example 2:
Input: n = 5 Output: [0,1,1,2,1,2] Explanation: 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101
Constraints:
0 <= n <= 105
Follow up:
- It is very easy to come up with a solution with a runtime of
O(n log n). Can you do it in linear timeO(n)and possibly in a single pass? - Can you do it without using any built-in function (i.e., like
__builtin_popcountin C++)?
class Solution:
def countBits(self, n: int) -> List[int]:
"""
assert Solution().countBits(5) == [0, 1, 1, 2, 1, 2]
assert Solution().countBits(2) == [0, 1, 1]
Reference problem solving ideas : Dynamic programming and bit operation ,dp[i] representative i There are several binary systems 1,
if i The end of the binary bit is 0, be dp[i]=dp[i>>1], Because the end is 0 了 ,1 The number of i The arithmetic shift right is the same
if i The end of the binary bit is 1, be dp[i]=dp[i-1]+1, Because the end is 1 了 , Is to make i-1 Binary bit of 1 Add one at the end of the present 1
Time complexity :O(n), Spatial complexity :O(n)
"""
dp = [0] * (n + 1)
for i in range(1, n + 1):
dp[i] = dp[i - 1] + 1 if i & 1 else dp[i >> 1]
return dp边栏推荐
猜你喜欢

leetcode 834. 树中距离之和

MySQL_ Query of data processing

SAP fi financial statement version setting

redis主备配置dockercompose版

leetcode 99.恢复二叉搜索树

Tianyi cloud digital government smart data center has passed the certification

130. Surrounded Regions

SAP development keys application SSCR keys application

Sap-abap- how to find a table and what related tables the fields have

SAP 客户端中文显示乱码问题
随机推荐
Recommend a virtual machine software for fast cluster building of M1 chip computers
vs code
Gradle notes
Writing a contract testing tool from scratch -- database design
257. Binary Tree Paths
SAP system cancels user setting ALV global layout
SNC processing failed SAP router certificate regeneration
Redis
RobotFramework中setUp的小技巧
OO2022第四单元作业总结
342. Power of Four
从零开始写一个契约测试工具——数据库设计
The solution of VPC network automatic configuration based on terraform
leetcode 834. 树中距离之和
别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!
Tis tutorial 04 client
think php环境搭建笔记
leetcode 829. 连续整数求和
Detailed explanation of rules and ideas for advance sale of deposit
File download vulnerability & file read vulnerability & file delete vulnerability