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 = 5
you 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/324124.html