forked from tangweikun/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
638cdce
commit fc9267d
Showing
5 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters