File tree 4 files changed +60
-5
lines changed
4 files changed +60
-5
lines changed Original file line number Diff line number Diff line change 1
1
{
2
- "presets" : [
3
- " es2015" ,
4
- " env"
5
- ]
6
- }
2
+ "presets" : [" es2015" , " env" ]
3
+ }
Original file line number Diff line number Diff line change
1
+ <!-- TODO: Translate Me -->
2
+
3
+ # number of 1 the binary
4
+
5
+ ## Description
6
+
7
+ * 任意给定一个 32 位无符号整数` n ` ,求` n ` 的二进制表示中 1 的个数
8
+
9
+ ## Example
10
+
11
+ ``` javascript
12
+ Input: 5
13
+ Output: 2
14
+
15
+ Input: 15
16
+ Output: 4
17
+ ```
Original file line number Diff line number Diff line change
1
+ export function numberOf1InBinary ( num , total = 1 ) {
2
+ if ( num === 0 ) return 0
3
+ if ( num === 1 ) return total
4
+ if ( num % 2 ) {
5
+ return numberOf1InBinary ( ( num - 1 ) / 2 , total + 1 )
6
+ }
7
+ return numberOf1InBinary ( num / 2 , total )
8
+ }
Original file line number Diff line number Diff line change
1
+ import { numberOf1InBinary } from '.'
2
+
3
+ test ( 'numberOf1InBinary-0' , ( ) => {
4
+ expect ( numberOf1InBinary ( 0 ) ) . toBe ( 0 )
5
+ } )
6
+
7
+ test ( 'numberOf1InBinary-1' , ( ) => {
8
+ expect ( numberOf1InBinary ( 1 ) ) . toBe ( 1 )
9
+ } )
10
+
11
+ test ( 'numberOf1InBinary-2' , ( ) => {
12
+ expect ( numberOf1InBinary ( 2 ) ) . toBe ( 1 )
13
+ } )
14
+
15
+ test ( 'numberOf1InBinary-3' , ( ) => {
16
+ expect ( numberOf1InBinary ( 7 ) ) . toBe ( 3 )
17
+ } )
18
+
19
+ test ( 'numberOf1InBinary-4' , ( ) => {
20
+ expect ( numberOf1InBinary ( 17 ) ) . toBe ( 2 )
21
+ } )
22
+
23
+ test ( 'numberOf1InBinary-5' , ( ) => {
24
+ expect ( numberOf1InBinary ( 32 ) ) . toBe ( 1 )
25
+ } )
26
+
27
+ test ( 'numberOf1InBinary-6' , ( ) => {
28
+ expect ( numberOf1InBinary ( 53 ) ) . toBe ( 4 )
29
+ } )
30
+
31
+ test ( 'numberOf1InBinary-7' , ( ) => {
32
+ expect ( numberOf1InBinary ( 111 ) ) . toBe ( 6 )
33
+ } )
You can’t perform that action at this time.
0 commit comments