One Pager Cheat Sheet
- Today's task involves writing a function that converts a decimal number to its binary representation; it requires understanding the definitions of
binary
anddecimal
, with the added constraints that the input will be a positive integer between 0 and1000000000
, and the expected time and space complexities areO(log n)
andO(1)
respectively. - The article provides steps to convert a decimal number to binary, using the division with remainder method, by repeatedly dividing by
2
and recording the remainders, which, when read from bottom to top, give the binary representation of the original decimal number. - The process of converting a decimal number to binary works by repeatedly dividing the decimal number by
2
and recording the remainder, symbolizing the sum of powers of2
that construct the original decimal number, yielding the binary representation. - The text outlines a coding approach to convert decimal numbers to binary, specifying that if a number is less than
1
, an empty string should be returned and detailing two cases: ifnum
is divisible by2
, and if it's not, whereby recursive operations are performed; the time and space complexity of this approach isO(logn)
.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
49
}
var assert = require('assert');
function decimalToBinary(num) {
if (num >= 1) {
if (num % 2) {
return decimalToBinary((num - 1) / 2) + 1;
} else {
return decimalToBinary(num / 2) + 0;
}
} else {
return '';
}
}
try {
assert.equal(decimalToBinary(3), 11);
console.log('PASSED: ' + 'decimalToBinary(3) should return 11');
} catch (err) {
console.log(err);
}
try {
assert.equal(decimalToBinary(8), 1000);
console.log('PASSED: ' + 'decimalToBinary(8) should return 1000');
} catch (err) {
console.log(err);
}
try {
assert.equal(decimalToBinary(1000), 1111101000);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
That's all we've got! Let's move on to the next tutorial.
If you had any problems with this tutorial, check out the main forum thread here.