加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 338. Counting Bits

发布时间:2020-12-14 07:06:16 所属栏目:百科 来源:网络整理
导读: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,2,2] . 题意:给定n

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
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读