Skip to content

Commit

Permalink
Merge branch 'Math' of https://github.com/soapyigu/LeetCode_Swift int…
Browse files Browse the repository at this point in the history
…o Math
  • Loading branch information
Yi Gu committed Aug 4, 2016
2 parents c0e308f + 8fc6f1d commit 40c8cdf
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
28 changes: 28 additions & 0 deletions Math/CountingBits.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* Question Link: https://leetcode.com/problems/counting-bits/
* Primary idea:
* bits[i] = bits[i - p] + 1, while p is the largest power of two that smaller than i;
*
* Time Complexity: O(n), Space Complexity: O(n)
*/

class CountingBits {
func countBits(num: Int) -> [Int] {
guard num > 0 else {
return [0]
}

var bits = [Int](count: num + 1, repeatedValue: 0)
var x = 1
for i in 1...num {
if i == x {
x = x << 1
bits[i] = 1
} else {
bits[i] = bits[i - (x >> 1)] + 1
}
}

return bits
}
}
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@
[Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/)| [Swift](./Math/ExcelSheetColumnNumber.swift)| Easy| O(n)| O(1)|
[Roman to Integer](https://leetcode.com/problems/roman-to-integer/)| [Swift](./Math/RomanToInteger.swift)| Easy| O(n)| O(n)|
[Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/)| [Swift](./Math/TrappingRainWater.swift)| Hard| O(n)| O(n)|
[Counting Bits](https://leetcode.com/problems/counting-bits/)| [Swift](./Math/CountingBits.swift)| Medium| O(n)| O(n)|

## Search
| Title | Solution | Difficulty | Time | Space |
Expand Down Expand Up @@ -308,7 +309,7 @@
| | 341 | [Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/) | Medium
| | 340 | [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/) &hearts; | Hard
| [Swift](./DP/NestedListWeightSum.swift) | 339 | [Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum/) &hearts; | Easy
| | 338 | [Counting Bits](https://leetcode.com/problems/counting-bits/) | Medium
| [Swift](./Math/CountingBits.swift) | 338 | [Counting Bits](https://leetcode.com/problems/counting-bits/) | Medium
| | 337 | [House Robber III](https://leetcode.com/problems/house-robber-iii/) | Medium
| | 336 | [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | Hard
| | 335 | [Self Crossing](https://leetcode.com/problems/self-crossing/) | Hard
Expand Down

0 comments on commit 40c8cdf

Please sign in to comment.