[LeetCode] Counting Bits

news/2024/6/14 19:10:51

Problem

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.

Example

For num = 5 you should return [0,1,1,2,1,2].

Follow up

It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

Hint

You should make use of what you have produced already.
Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
Or does the odd/even status of the number help you in calculating the number of 1s?

Note

应用公式f[i] = f[i/2] + (i%2);
并优化此公式为f[i] = f[i>>2] + (i&1),减少计算时间。

Solution

public class Solution {
    public int[] countBits(int num) {
        int[] dp = new int[num+1];
        for (int i = 1; i <= num; i++) dp[i] = dp[i>>1] + (i&1);
        return dp;
    }
}

http://www.niftyadmin.cn/n/2525440.html

相关文章

Low-level I/O 和 File System Interface

Low-level I/O 和 File System Interface 2008-10-16 15:09 482人阅读 评论(1) 收藏 举报fileinterfacesystemdescriptorstructstream1. 为什么需要使用 low-level I/O&#xff0c;glibc 里面提到了一些情形&#xff0c;对大量二进制数据进行操作&#xff0c;某些文件上的操作只…

CG cosh, exp, sinh, smoothstep, tanh, perlin_easeCurve1/2 曲线

文章目录cosh为何叫双曲线exp(x)曲线exp(-x) 曲线exp(x)exp(-x) 两曲线叠加调整x0时&#xff0c;y0调整x-2 or 2时&#xff0c;y1exp(-x*x)sinhsmoothsteptanhperlin noise ease curve 1perlin noise ease curve 2Summaryexcel 文件Referencesxxxh 中的h>hyperbolic&#xf…

Bash的输入输出重定向

Bash的输入输出重定向 此页由Linux Wiki用户Chenxing于2012年12月18日 (星期二) 07:58的最后更改。 在linuxCook的工作基础上。使用Bash可以方便的用<和>实现输出输入的重定向&#xff0c;本文讨论重定向的一些细节和技巧。本文介绍部分是对Bash Quick Reference相关内容…

Unity Shader PostProcessing - 1 - 后处理概念

(加粗的内容需要留意) 什么叫PostProcessing&#xff1f; Post Processing 中文直译&#xff1a;后处理&#xff08;以前我是不知道是怎么回事&#xff0c;总觉得好高端的感觉&#xff0c;-_-&#xff09; 我们知道&#xff1a;在场景的所有需要渲染的对象&#xff0c;渲染完后…

文件描述符和文件流之间的转换

文件描述符和文件流之间的转换 2009-11-24 17:30 345人阅读 评论(0) 收藏 举报streamfilesocketFILE *fdopen(int fildes, const char *type); 这个函数很有用的&#xff0c;功能是将一个流关联到一个打开的文件号filedes上&#xff0c; 该filedes可以是open、pipe、dup、dup2…

Unity Shader PostProcessing - 2 - 边缘检测

边缘检测的算法有很多种 这里介绍的是其中的一部分 SobelPrewittRobertLine 这些卷积核&#xff0c;都是final g越大&#xff0c;越可能是边缘 Sobel (-1,1), (0,1), (1,1)与(-1,-1),(0,-1),(1,-1)的亮度差距越大&#xff0c;特别是左右、上下的差异越大&#xff0c;则final…

switch表达式类型

switch表达式类型 一般格式&#xff1a; switch &#xff08;表达式&#xff09; &#xff5b; case 常量标号1&#xff1a;语句序列1; break; case 常量标号2&#xff1a;语句序列2; break; … case 常量标号n&#xff1a;语句序列n; break; default&#xff1a; 语句S; &…

iOS开发系列之运动事件

前面我们主要介绍了触摸事件以及由触摸事件引出的手势识别&#xff0c;下面我们简单介绍一下运动事件。在iOS中和运动相关的有三个事件:开始运动、结束运动、取消运动。 监听运动事件对于UI控件有个前提就是监听对象必须是第一响应者&#xff08;对于UIViewController视图控制器…