Swift 338. Counting Bits

Swift 338. Counting Bits,第1张

概述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 s

Given a non negative integer numbernum. For every numbersiin the range0 ≤ i ≤ numcalculate the number of 1's in their binary representation and return them as an array.

Example:
Fornum = 5you should return[0,1,2,2].

题意:给定num,计算从0到num中的每个数的二进制中1的个数

解题思路:分奇偶数进行处理,奇数n包含1的个数等于n/2 包含1的个数 +1,因为奇数的二进制的低位为1,除2之后相当于右移一位,少了一个1,所以要加1;同理,偶数不需要加1,等于n/2 包含1的个数

程序如下:

func countBits(num: Int) -> [Int] {            var arr:[Int] = [0]    if num == 0  {return arr}    for i in 1...num    {         if i%2 == 1        {            arr.append(arr[i/2]+1)        }else{            arr.append(arr[i/2])        }            }    return arr    }
总结

以上是内存溢出为你收集整理的Swift 338. Counting Bits全部内容,希望文章能够帮你解决Swift 338. Counting Bits所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1077734.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-27
下一篇2022-05-27

发表评论

登录后才能评论

评论列表(0条)

    保存