Skip to content

Commit 502e11e

Browse files
authored
algorithm: decimal to binary (#23)
1 parent 94c0594 commit 502e11e

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/Maths/BinaryConvert.ts

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @function BinaryConvert
3+
* @description Convert the decimal to binary.
4+
* @param {number} num - The input integer
5+
* @return {string} - 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+
export const BinaryConvert = (num: number): string => {
12+
let binary = ''
13+
14+
while (num !== 0) {
15+
binary = (num % 2) + binary
16+
num = Math.floor(num / 2)
17+
}
18+
19+
return binary
20+
}

src/Maths/test/BinaryConvert.test.ts

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { BinaryConvert } from '../BinaryConvert'
2+
3+
describe('BinaryConvert', () => {
4+
it('should return the correct value', () => {
5+
expect(BinaryConvert(4)).toBe('100')
6+
})
7+
it('should return the correct value', () => {
8+
expect(BinaryConvert(12)).toBe('1100')
9+
})
10+
it('should return the correct value of the sum from two number', () => {
11+
expect(BinaryConvert(12 + 2)).toBe('1110')
12+
})
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+
})
22+
})

0 commit comments

Comments
 (0)