Last active
April 13, 2025 07:39
-
-
Save jbhoot/9a20bd4a5f71fc7f88fffed6ddba64de to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Explanation: | |
// In decimal system: 142 = 100 + 40 + 2 = (1 * 10^2) + (4 * 10^1) + (2 * 10^0) = 142 | |
// In binary system: 101 = (1 * 2^2) + (0 * 2^1) + (1 * 2^0) = 4 + 0 + 1 = 5 | |
function binaryToDecimal(v) { | |
const first = v[0]; | |
const exp = v.length - 1; | |
const val = parseInt(first) * (2 ** exp); | |
if (v.length === 0) { | |
return NaN; | |
} else if (v.length === 1) { | |
return val; | |
} else { | |
const rest = v.slice(1); | |
return val + binaryToDecimal(rest); | |
} | |
} | |
binaryToDecimal("100"); // 4 | |
binaryToDecimal([1, 0, 0]); // 4 | |
binaryToDecimal("100001"); // 33 | |
binaryToDecimal("11111111"); // 255 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Rough explanation: | |
// If v is 0, then return "0". | |
// 1. Modulo divide v by 2. Collect this first remainder as the last digit of the final result - binary equivalent of v. | |
// 2. Modulo divide resulting quotient by 2. Collect the remainder as the nth from the last digit of the final result. | |
// 3. Repeat step 2 until quotient is 0. | |
// 4. The collected remainders is the binary equivalent of v. | |
// Example: v = 9 | |
// 9 mod 2 = 4 (quotient), 1 (remainder). result: "1" | |
// 4 mod 2 = 2 (quotient), 0 (remainder). result: "01" | |
// 2 mod 2 = 1 (quotient), 0 (remainder). result: "001" | |
// 2 mod 1 = 0 (quotient), 1 (remainder). result: "1001" | |
// Final Result: "1001" | |
function decimalToUnsignedBinary(v) { | |
const absV = Math.abs(v); | |
if (absV === 0) { | |
return "0"; | |
} else if (absV === 1) { | |
return "1"; | |
} else { | |
const quotient = Math.floor(absV / 2); | |
const remainder = absV % 2; | |
return decimalToUnsignedBinary(quotient) + remainder; | |
} | |
} | |
decimalToUnsignedBinary(0); // => "0" | |
decimalToUnsignedBinary(1); // => "1" | |
decimalToUnsignedBinary(10); // => "1010" | |
decimalToUnsignedBinary(33); // => "100001" | |
decimalToUnsignedBinary(-33); // => "100001" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment