Skip to content

Commit

Permalink
chore: find the binary sum of numbers (#191)
Browse files Browse the repository at this point in the history
  • Loading branch information
Suryac72 authored Oct 14, 2023
1 parent d2d28f0 commit 9b28624
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
27 changes: 27 additions & 0 deletions bit_manipulation/add_binary.ts
Original file line number Diff line number Diff line change
@@ -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('');
}
33 changes: 33 additions & 0 deletions bit_manipulation/test/add_binary.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});

0 comments on commit 9b28624

Please sign in to comment.