Last active
December 24, 2023 22:55
-
-
Save primaryobjects/c94d94ff5a464b1ab1a1b84156c5eddc to your computer and use it in GitHub Desktop.
Add two binary strings. Solved in TypeScript. https://leetcode.com/problems/add-binary
This file contains 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
// Add two binary strings directly by using a carry bit. | |
const addBinary = (a:string, b:string): string => { | |
let result: string = ''; | |
let i=0; | |
let carry = 0; | |
while (i < a.length || i < b.length) { | |
let a_bit = '0'; | |
let b_bit = '0'; | |
let bit = 0; | |
if (i < a.length) { | |
a_bit = a[a.length - i - 1]; | |
} | |
if (i < b.length) { | |
b_bit = b[b.length - i - 1]; | |
} | |
const value = parseInt(a_bit) + parseInt(b_bit) + carry; | |
if (value == 0) { | |
bit = 0; | |
carry = 0; | |
} | |
else if (value == 1) { | |
bit = 1; | |
carry = 0; | |
} | |
else if (value == 2) { | |
bit = 0; | |
carry = 1; | |
} | |
else if (value == 3) { | |
bit = 1; | |
carry = 1; | |
} | |
result = bit + result; | |
i++; | |
} | |
result = carry ? carry + result : result; | |
return result; | |
} |
This file contains 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
// Add two binary strings with helper methods to convert between binary and decimal representations. | |
// Then add the decimal values and convert the result back to binary. | |
// This is one way to implement binary addition, but there are other methods that can be done directly on the binary strings, such as using a carry bit. | |
const toBase10 = (s: string): number => { | |
let total = 0; | |
for (let i=0; i<s.length; i++) { | |
const bit = parseInt(s[s.length - i - 1]); | |
const val = Math.pow(2, i) * bit; | |
total += val; | |
} | |
return total; | |
}; | |
const toBase2 = (n: number): string => { | |
let result = ''; | |
result = n.toString(2); | |
return result; | |
}; | |
function addBinary(a: string, b: string): string { | |
// Convert to base10. | |
const a_val = toBase10(a); | |
const b_val = toBase10(b); | |
const total = a_val + b_val; | |
// Convert result to binary. | |
return toBase2(total); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment