mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
merge: Binary Convert (#865)
* Binary Convert * Update link * add more test cases
This commit is contained in:
@ -1,10 +1,25 @@
|
|||||||
const BinaryConvert = (number) => {
|
/**
|
||||||
const result = []
|
* @function BinaryConvert
|
||||||
let i
|
* @description Convert the decimal to binary.
|
||||||
for (i = number; i > 0; i = parseInt(i / 2)) {
|
* @param {Integer} num - The input integer
|
||||||
result.push(i % 2) // push the value (remainder)to array
|
* @return {Integer} - Binary of num.
|
||||||
} return Number(result.reverse().join(''))
|
* @see [BinaryConvert](https://www.programiz.com/javascript/examples/decimal-binary)
|
||||||
// reverse index of array as string ,join and change the type of value to become Number
|
* @example BinaryConvert(12) = 1100
|
||||||
|
* @example BinaryConvert(12 + 2) = 1110
|
||||||
|
*/
|
||||||
|
|
||||||
|
const BinaryConvert = (num) => {
|
||||||
|
let power = 1
|
||||||
|
let binary = 0
|
||||||
|
|
||||||
|
while (num) {
|
||||||
|
const rem = num % 2
|
||||||
|
num = Math.floor(num / 2)
|
||||||
|
binary = rem * power + binary
|
||||||
|
power *= 10
|
||||||
|
}
|
||||||
|
|
||||||
|
return binary
|
||||||
}
|
}
|
||||||
// call function and value as parameter to passing the value
|
|
||||||
export { BinaryConvert }
|
export { BinaryConvert }
|
||||||
|
@ -1,10 +1,22 @@
|
|||||||
import { BinaryConvert } from '../BinaryConvert'
|
import { BinaryConvert } from '../BinaryConvert'
|
||||||
|
|
||||||
describe('Binary Convert', () => {
|
describe('BinaryConvert', () => {
|
||||||
|
it('should return the correct value', () => {
|
||||||
|
expect(BinaryConvert(4)).toBe(100)
|
||||||
|
})
|
||||||
it('should return the correct value', () => {
|
it('should return the correct value', () => {
|
||||||
expect(BinaryConvert(12)).toBe(1100)
|
expect(BinaryConvert(12)).toBe(1100)
|
||||||
})
|
})
|
||||||
it('should return the correct value of the sum from two number', () => {
|
it('should return the correct value of the sum from two number', () => {
|
||||||
expect(BinaryConvert(12 + 2)).toBe(1110)
|
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)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
Reference in New Issue
Block a user