Skip to content

Commit 9b28624

Browse files
authored
chore: find the binary sum of numbers (#191)
1 parent d2d28f0 commit 9b28624

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

bit_manipulation/add_binary.ts

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Adds two binary strings and returns the result as a binary string.
3+
*
4+
* @param firstBinaryNo - The first binary string.
5+
* @param secondBinaryNo - The second binary string.
6+
* @returns The binary sum of the input strings.
7+
*/
8+
export function addBinary(firstBinaryNo: string, secondBinaryNo: string): string {
9+
let lengthOfFirstNumber: number = firstBinaryNo.length - 1;
10+
let lengthOfSecondNumber: number = secondBinaryNo.length - 1;
11+
let solution: string[] = [];
12+
let carry: number = 0;
13+
14+
while ( lengthOfFirstNumber >= 0 || lengthOfSecondNumber >= 0) {
15+
let sum: number = carry;
16+
if (lengthOfFirstNumber >= 0) sum += parseInt(firstBinaryNo.charAt(lengthOfFirstNumber));
17+
if (lengthOfSecondNumber >= 0) sum += parseInt(secondBinaryNo.charAt(lengthOfSecondNumber));
18+
solution.push((sum % 2).toString());
19+
carry = Math.floor(sum / 2);
20+
lengthOfFirstNumber--;
21+
lengthOfSecondNumber--;
22+
}
23+
24+
if (carry !== 0) solution.push(carry.toString());
25+
26+
return solution.reverse().join('');
27+
}
+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { addBinary } from "../add_binary";
2+
3+
describe('Add Binary Number', () => {
4+
it('should add two binary numbers with no carry', () => {
5+
const result = addBinary('1101', '1011');
6+
expect(result).toBe('11000');
7+
});
8+
9+
it('should add two binary numbers with carry', () => {
10+
const result = addBinary('1111', '1111');
11+
expect(result).toBe('11110');
12+
});
13+
14+
it('should add two different-length binary numbers', () => {
15+
const result = addBinary('1101', '111');
16+
expect(result).toBe('10100');
17+
});
18+
19+
it('should add two empty binary numbers', () => {
20+
const result = addBinary('', '');
21+
expect(result).toBe('');
22+
});
23+
24+
it('should add one empty binary number to a non-empty number', () => {
25+
const result = addBinary('1010', '');
26+
expect(result).toBe('1010');
27+
});
28+
29+
it('should add one non-empty binary number to an empty number', () => {
30+
const result = addBinary('', '1101');
31+
expect(result).toBe('1101');
32+
});
33+
});

0 commit comments

Comments
 (0)