Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- func countBits(num: Int) -> [Int] {
- var nums = [Int](count: num+1, repeatedValue: 0)
- if num == 0 { // if num is 0
- return nums
- }
- for i in 1...num {
- nums[i] = binaryOnes(i)
- }
- return nums
- }
- func binaryOnes(num: Int) -> Int {
- var num = num
- var count = 0
- repeat {
- if num % 2 == 0 { // even numbers
- num /= 2
- } else { // all odd numbers
- num = (num-1)/2
- count += 1
- }
- } while num > 1
- if num == 1 { // when num is 1 at the end
- count += 1
- }
- return count
- }
- }
- repeat { ... } while num > 1
- while num > 0 { ... }
- func binaryOnes(num: Int) -> Int {
- var num = num
- var count = 0
- while num > 0 {
- if num % 2 == 0 { // even numbers
- num /= 2
- } else { // all odd numbers
- num = (num-1)/2
- count += 1
- }
- }
- return count
- }
- func binaryOnes(num: Int) -> Int {
- var num = num
- var count = 0
- while num > 0 {
- count += num % 2
- num /= 2
- }
- return count
- }
- func countBits(num: Int) -> [Int] {
- var nums = [Int](count: num+1, repeatedValue: 0)
- for i in 1...num {
- nums[i] = binaryOnes(i)
- }
- return nums
- }
- func countBits(upTo: Int) -> [Int] {
- return (0...upTo).map(binaryOnes)
- }
- bitCount(n) = bitCount(n/2) + (n % 2)
- func countBits1(upTo: Int) -> [Int] {
- var result = [ 0 ]
- for i in 1...upTo {
- result.append(result[i/2] + (i % 2))
- }
- return result
- }
- func countBits(_ num: Int) -> [Int] {
- var ans = [Int]()
- for i in 0...num {
- ans.append(getOnes(x: i))
- }
- return ans
- }
- func getOnes(x: Int) -> Int {
- return String(x, radix: 2).filter {
- $0 == "1"
- }.count
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement