Skip to content

algorithm: decimal to binary #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 2, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/Maths/BinaryConvert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @function BinaryConvert
* @description Convert the decimal to binary.
* @param {number} num - The input integer
* @return {string} - Binary of num.
* @see [BinaryConvert](https://www.programiz.com/javascript/examples/decimal-binary)
* @example BinaryConvert(12) = 1100
* @example BinaryConvert(12 + 2) = 1110
*/

export const BinaryConvert = (num: number): string => {
let binary = ''

while (num !== 0) {
binary = (num % 2) + binary
num = Math.floor(num / 2)
}

return binary
}
22 changes: 22 additions & 0 deletions src/Maths/test/BinaryConvert.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { BinaryConvert } from '../BinaryConvert'

describe('BinaryConvert', () => {
it('should return the correct value', () => {
expect(BinaryConvert(4)).toBe('100')
})
it('should return the correct value', () => {
expect(BinaryConvert(12)).toBe('1100')
})
it('should return the correct value of the sum from two number', () => {
expect(BinaryConvert(12 + 2)).toBe('1110')
})
it('should return the correct value of the subtract from two number', () => {
expect(BinaryConvert(245 - 56)).toBe('10111101')
})
it('should return the correct value', () => {
expect(BinaryConvert(254)).toBe('11111110')
})
it('should return the correct value', () => {
expect(BinaryConvert(63483)).toBe('1111011111111011')
})
})