[swift] LeetCode 338. Counting Bits

栏目: Swift · 发布时间: 5年前

内容简介: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].

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.

func countBits(_ num: Int) -> [Int] {
    var arr = Array(repeating: 0, count: num+1), i = 0
    while i <= num {
        arr[i] = i.nonzeroBitCount
        i += 1
    }
 
    return arr
}
[swift] LeetCode 338. Counting Bits [swift] LeetCode 338. Counting Bits

(随着网站访问量的激增,服务器配置只得一再升级以维持网站不“404 Not Found”,所以网站的维护费用也在不断上涨……(目前的阿里云服务器ECS+云数据库RDS+域名购买+七牛云的费用是2200元/年),为了能不放弃该网站,所以我又把打赏链接放上来啦~所有打赏金额都会被记账并投入博客维护中,感谢厚爱,多多关照~)


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

机器学习及其应用2007

机器学习及其应用2007

周志华 编 / 清华大学 / 2007-10 / 37.00元

机器学习是人工智能的一个核心研究领域,也是近年来计算机科学中最活跃的研究分支之一。目前,机器学习技术不仅在计算机科学的众多领域中大显身手,还成为一些交叉学科的重要支撑技术。本书邀请相关领域的专家撰文,以综述的形式介绍机器学习中一些领域的研究进展。全书共分13章,内容涉及高维数据降维、特征选择、支持向量机、聚类、强化学习、半监督学习、复杂网络、异构数据、商空间、距离度量以及机器学习在自然语言处理中的......一起来看看 《机器学习及其应用2007》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

MD5 加密
MD5 加密

MD5 加密工具