File tree Expand file tree Collapse file tree 2 files changed +31
-8
lines changed Expand file tree Collapse file tree 2 files changed +31
-8
lines changed Original file line number Diff line number Diff line change 33 * 5.6 Conversion: Write a function to determine the number of bits you would need to flip to convert integer A to integer B.
44
55 EXAMPLE
6- Input: 29 (or: 111131 ), 15 (or: 131111 )
6+ Input: 29 (or: 111101 ), 15 (or: 101111 )
77
88 Output: 2
99
1010 Hints: #336, #369
1111 *
12- * @param number
12+ * @param number1
13+ * @param number2
1314 */
14- function conversion ( number ) {
15+ function conversion ( number1 , number2 ) {
16+ return countOnes ( number1 ^ number2 ) ;
17+ }
18+
19+ function countOnes ( num ) {
20+ let ones = 0 ;
21+
22+ while ( num > 0 ) {
23+ if ( num & 1 ) {
24+ ones ++ ;
25+ }
26+ num >>= 1 ;
27+ }
1528
29+ return ones ;
1630}
1731
18- module . exports = conversion ;
32+ module . exports = conversion ;
33+
34+
35+ /*
36+ xor
37+
38+
39+
40+
41+ */
Original file line number Diff line number Diff line change @@ -2,11 +2,11 @@ const expect = require('chai').expect;
22const conversion = require ( './06-conversion' ) ;
33
44describe ( 'Bit Manipulation: conversion' , function ( ) {
5- it ( 'power of two ' , function ( ) {
6- expect ( conversion ( 0b0 ) ) . to . equal ( true ) ;
5+ it ( '29 and 15 ' , function ( ) {
6+ expect ( conversion ( 0b111101 , 0b101111 ) ) . to . equal ( 2 ) ;
77 } ) ;
88
9- it ( 'no power of two ' , function ( ) {
10- expect ( conversion ( 0b111 ) ) . to . equal ( false ) ;
9+ it ( 'one and zero ' , function ( ) {
10+ expect ( conversion ( 0b01 , 0b00 ) ) . to . equal ( 1 ) ;
1111 } ) ;
1212} ) ;
You can’t perform that action at this time.
0 commit comments