Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. class Solution {
  2. func countBits(num: Int) -> [Int] {
  3. var nums = [Int](count: num+1, repeatedValue: 0)
  4. if num == 0 { // if num is 0
  5. return nums
  6. }
  7. for i in 1...num {
  8. nums[i] = binaryOnes(i)
  9. }
  10. return nums
  11. }
  12. func binaryOnes(num: Int) -> Int {
  13. var num = num
  14. var count = 0
  15. repeat {
  16. if num % 2 == 0 { // even numbers
  17. num /= 2
  18. } else { // all odd numbers
  19. num = (num-1)/2
  20. count += 1
  21. }
  22. } while num > 1
  23. if num == 1 { // when num is 1 at the end
  24. count += 1
  25. }
  26. return count
  27. }
  28. }
  29.  
  30. repeat { ... } while num > 1
  31.  
  32. while num > 0 { ... }
  33.  
  34. func binaryOnes(num: Int) -> Int {
  35. var num = num
  36. var count = 0
  37. while num > 0 {
  38. if num % 2 == 0 { // even numbers
  39. num /= 2
  40. } else { // all odd numbers
  41. num = (num-1)/2
  42. count += 1
  43. }
  44. }
  45. return count
  46. }
  47.  
  48. func binaryOnes(num: Int) -> Int {
  49. var num = num
  50. var count = 0
  51. while num > 0 {
  52. count += num % 2
  53. num /= 2
  54. }
  55. return count
  56. }
  57.  
  58. func countBits(num: Int) -> [Int] {
  59. var nums = [Int](count: num+1, repeatedValue: 0)
  60. for i in 1...num {
  61. nums[i] = binaryOnes(i)
  62. }
  63. return nums
  64. }
  65.  
  66. func countBits(upTo: Int) -> [Int] {
  67. return (0...upTo).map(binaryOnes)
  68. }
  69.  
  70. bitCount(n) = bitCount(n/2) + (n % 2)
  71.  
  72. func countBits1(upTo: Int) -> [Int] {
  73. var result = [ 0 ]
  74. for i in 1...upTo {
  75. result.append(result[i/2] + (i % 2))
  76. }
  77. return result
  78. }
  79.  
  80. func countBits(_ num: Int) -> [Int] {
  81. var ans = [Int]()
  82.  
  83. for i in 0...num {
  84. ans.append(getOnes(x: i))
  85. }
  86. return ans
  87. }
  88.  
  89. func getOnes(x: Int) -> Int {
  90. return String(x, radix: 2).filter {
  91. $0 == "1"
  92. }.count
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement