Swift 338. Counting Bits
来源:互联网 发布:大数据技术入门 编辑:程序博客网 时间:2024/06/05 02:03
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]
.
题意:给定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 }
1 0
- Swift 338. Counting Bits
- [leetcode] 338. Counting Bits
- 338. Counting Bits
- leetcode 338. Counting Bits
- LeetCodeOJ:338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode#338. Counting Bits
- 338. Counting Bits
- [LeetCode] 338. Counting Bits
- LeetCode 338. Counting Bits
- 338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode-338. Counting Bits
- LeetCode *** 338. Counting Bits
- 338. Counting Bits
- (leetcode) 338. Counting Bits
- #leetcode#338. Counting Bits
- LeetCode 338. Counting Bits
- 比较ArrayList、LinkedList、Vector
- AngularJS视图和$scope的世界
- 杭电1172
- 器普.net语法V1.0发布
- $scope 的生命周期
- Swift 338. Counting Bits
- (合并委托)京东研发笔试题
- 大学课程与个人项目感悟
- HTC V版M7解锁刷机笔记
- AngularJS控制器嵌套(作用域包含作用域)
- 一、runtime之元素认知(一)
- leetcode227-Basic Calculator II(简单计算器的实现)
- Spring框架之<context:property-placeholder />元素
- instancetype代替id进行实例化