File tree Expand file tree Collapse file tree 2 files changed +36
-9
lines changed Expand file tree Collapse file tree 2 files changed +36
-9
lines changed Original file line number Diff line number Diff line change 1- const BinaryConvert = ( number ) => {
2- const result = [ ]
3- let i
4- for ( i = number ; i > 0 ; i = parseInt ( i / 2 ) ) {
5- result . push ( i % 2 ) // push the value (remainder)to array
6- } return Number ( result . reverse ( ) . join ( '' ) )
7- // reverse index of array as string ,join and change the type of value to become Number
1+ /**
2+ * @function BinaryConvert
3+ * @description Convert the decimal to binary.
4+ * @param {Integer } num - The input integer
5+ * @return {Integer } - Binary of num.
6+ * @see [BinaryConvert](https://www.programiz.com/javascript/examples/decimal-binary)
7+ * @example BinaryConvert(12) = 1100
8+ * @example BinaryConvert(12 + 2) = 1110
9+ */
10+
11+ const BinaryConvert = ( num ) => {
12+ let power = 1
13+ let binary = 0
14+
15+ while ( num ) {
16+ const rem = num % 2
17+ num = Math . floor ( num / 2 )
18+ binary = rem * power + binary
19+ power *= 10
20+ }
21+
22+ return binary
823}
9- // call function and value as parameter to passing the value
24+
1025export { BinaryConvert }
Original file line number Diff line number Diff line change 11import { BinaryConvert } from '../BinaryConvert'
22
3- describe ( 'Binary Convert' , ( ) => {
3+ describe ( 'BinaryConvert' , ( ) => {
4+ it ( 'should return the correct value' , ( ) => {
5+ expect ( BinaryConvert ( 4 ) ) . toBe ( 100 )
6+ } )
47 it ( 'should return the correct value' , ( ) => {
58 expect ( BinaryConvert ( 12 ) ) . toBe ( 1100 )
69 } )
710 it ( 'should return the correct value of the sum from two number' , ( ) => {
811 expect ( BinaryConvert ( 12 + 2 ) ) . toBe ( 1110 )
912 } )
13+ it ( 'should return the correct value of the subtract from two number' , ( ) => {
14+ expect ( BinaryConvert ( 245 - 56 ) ) . toBe ( 10111101 )
15+ } )
16+ it ( 'should return the correct value' , ( ) => {
17+ expect ( BinaryConvert ( 254 ) ) . toBe ( 11111110 )
18+ } )
19+ it ( 'should return the correct value' , ( ) => {
20+ expect ( BinaryConvert ( 63483 ) ) . toBe ( 1111011111111011 )
21+ } )
1022} )
You can’t perform that action at this time.
0 commit comments