diff --git a/bit_manipulation/add_binary.ts b/bit_manipulation/add_binary.ts new file mode 100644 index 00000000..ebc05440 --- /dev/null +++ b/bit_manipulation/add_binary.ts @@ -0,0 +1,27 @@ +/** + * Adds two binary strings and returns the result as a binary string. + * + * @param firstBinaryNo - The first binary string. + * @param secondBinaryNo - The second binary string. + * @returns The binary sum of the input strings. + */ +export function addBinary(firstBinaryNo: string, secondBinaryNo: string): string { + let lengthOfFirstNumber: number = firstBinaryNo.length - 1; + let lengthOfSecondNumber: number = secondBinaryNo.length - 1; + let solution: string[] = []; + let carry: number = 0; + + while ( lengthOfFirstNumber >= 0 || lengthOfSecondNumber >= 0) { + let sum: number = carry; + if (lengthOfFirstNumber >= 0) sum += parseInt(firstBinaryNo.charAt(lengthOfFirstNumber)); + if (lengthOfSecondNumber >= 0) sum += parseInt(secondBinaryNo.charAt(lengthOfSecondNumber)); + solution.push((sum % 2).toString()); + carry = Math.floor(sum / 2); + lengthOfFirstNumber--; + lengthOfSecondNumber--; + } + + if (carry !== 0) solution.push(carry.toString()); + + return solution.reverse().join(''); +} diff --git a/bit_manipulation/test/add_binary.test.ts b/bit_manipulation/test/add_binary.test.ts new file mode 100644 index 00000000..e8ce1776 --- /dev/null +++ b/bit_manipulation/test/add_binary.test.ts @@ -0,0 +1,33 @@ +import { addBinary } from "../add_binary"; + +describe('Add Binary Number', () => { + it('should add two binary numbers with no carry', () => { + const result = addBinary('1101', '1011'); + expect(result).toBe('11000'); + }); + + it('should add two binary numbers with carry', () => { + const result = addBinary('1111', '1111'); + expect(result).toBe('11110'); + }); + + it('should add two different-length binary numbers', () => { + const result = addBinary('1101', '111'); + expect(result).toBe('10100'); + }); + + it('should add two empty binary numbers', () => { + const result = addBinary('', ''); + expect(result).toBe(''); + }); + + it('should add one empty binary number to a non-empty number', () => { + const result = addBinary('1010', ''); + expect(result).toBe('1010'); + }); + + it('should add one non-empty binary number to an empty number', () => { + const result = addBinary('', '1101'); + expect(result).toBe('1101'); + }); +}); \ No newline at end of file