diff --git a/README.md b/README.md index 855d25d..32f0520 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/src/countingBits/README.md b/src/countingBits/README.md new file mode 100644 index 0000000..4b5d9d5 --- /dev/null +++ b/src/countingBits/README.md @@ -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) diff --git a/src/countingBits/index.ts b/src/countingBits/index.ts new file mode 100644 index 0000000..9334745 --- /dev/null +++ b/src/countingBits/index.ts @@ -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 +} diff --git a/src/countingBits/test.ts b/src/countingBits/test.ts new file mode 100644 index 0000000..65121d3 --- /dev/null +++ b/src/countingBits/test.ts @@ -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]) +}) diff --git a/src/index.ts b/src/index.ts index 5bf5037..c08a0b0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -131,3 +131,4 @@ export * from './sumOfTwoIntegers' export * from './jewelsAndStones' export * from './numberOfBoomerangs' export * from './isomorphicStrings' +export * from './countingBits'