Skip to content

Commit

Permalink
✨ Counting Bits
Browse files Browse the repository at this point in the history
  • Loading branch information
tangweikun committed Feb 22, 2018
1 parent 638cdce commit fc9267d
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,3 +154,4 @@ npm run test
| 130 | [JewelsAndStones](src/jewelsAndStones/index.ts) | [:green_book:](src/jewelsAndStones/README.md) | Easy | [LeetCode](https://leetcode.com/problems/jewels-and-stones) | HashTable |
| 131 | [NumberOfBoomerangs](src/numberOfBoomerangs/index.ts) | [:green_book:](src/numberOfBoomerangs/README.md) | Easy | [LeetCode](https://leetcode.com/problems/number-of-boomerangs) | HashTable |
| 132 | [IsomorphicStrings](src/isomorphicStrings/index.ts) | [:green_book:](src/isomorphicStrings/README.md) | Easy | [LeetCode](https://leetcode.com/problems/isomorphic-strings) | HashTable |
| 133 | [CountingBits](src/countingBits/index.ts) | [:green_book:](src/countingBits/README.md) | Easy | [LeetCode](https://leetcode.com/problems/counting-bits) | Bit |
12 changes: 12 additions & 0 deletions src/countingBits/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# 133.Counting Bits

## Description

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].

## From

[LeetCode](https://leetcode.com/problems/counting-bits)
20 changes: 20 additions & 0 deletions src/countingBits/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export function countBits(num: number) {
let res = []
let i = 0
while (i <= num) {
res.push(getBits(i))
i++
}

return res
}

const getBits = (num: number) => {
let res = 0
while (num > 0) {
res += num & 1
num >>= 1
}

return res
}
13 changes: 13 additions & 0 deletions src/countingBits/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { countBits } from '.'

test('CountingBits-1', () => {
expect(countBits(5)).toEqual([0, 1, 1, 2, 1, 2])
})

test('CountingBits-2', () => {
expect(countBits(6)).toEqual([0, 1, 1, 2, 1, 2, 2])
})

test('CountingBits-3', () => {
expect(countBits(0)).toEqual([0])
})
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,4 @@ export * from './sumOfTwoIntegers'
export * from './jewelsAndStones'
export * from './numberOfBoomerangs'
export * from './isomorphicStrings'
export * from './countingBits'

0 comments on commit fc9267d

Please sign in to comment.