Posted on by Kalkicode
Code Bit Logic

BCD addition of two numbers in typescript

Ts program for BCD addition of two numbers. Here problem description and other solutions.

/*
   TypeScript program for
   BCD addition of two decimal numbers
*/
class Addition
{
	// Get valid value
	public string getValue(num: number)
	{
		if (num >= 0 && num <= 9)
		{
			return (num + parseInt('0')).toString();
		}
		else
		{
			return (num - 10 + parseInt('A')).toString();
		}
	}
	// Get 4 bit binary value of a digit
	public string binaryValue(num: number, extra: boolean)
	{
		var result = "";
		var n = num;
		while (n > 0)
		{
			result = (this.getValue(n % 2)) + result;
			n = parseInt(n / 2);
		}
		if (extra == true)
		{
			// When need to include extra bit
			n = result.length;
			while (n < 4)
			{
				result = "0" + result;
				n++;
			}
		}
		return result;
	}
	// Find BCD addition of given x and y
	public bcdAddition(x: number, y: number)
	{
		var sum = x + y;
		if (sum < 0)
		{
			return;
		}
		var ans = "";
		while (sum > 9)
		{
			ans = this.binaryValue(sum % 10, true) + ans;
			sum = parseInt(sum / 10);
		}
		// Add a first bit
		ans = this.binaryValue(sum % 10, false) + ans;
		// Display calculated result
		console.log(" (" + x + " + " + y + ") : " + ans);
	}
	public static main(args: string[])
	{
		var task = new Addition();
		// Test A
		//     x = 12  
		//     y = 6   
		// ======================
		// x + y = 18 => (1 = 1) (8 = 1000)  
		//      (11000)   
		//
		task.bcdAddition(12, 6);
		// Test B
		//     x = 7  
		//     y = 18  
		// ======================
		//        25 => 
		//  (2 = (10) 5 (0101))    
		//       (100101)  
		task.bcdAddition(7, 18);
		// Test C
		//     x = 45   
		//     y = 32   
		// ======================
		//         77
		// (7 = 111) (7 = 0111)
		//     (1110111)  
		task.bcdAddition(45, 32);
		// Test D
		//     x = 111   
		//     y = 132   
		// ======================
		//         243
		// (2 = 10) (4 = 0100) (3 = 0011)
		//    (1001000011)  
		task.bcdAddition(111, 132);
	}
}
Addition.main([]);
/*
 file : code.ts
 tsc --target es6 code.ts
 node code.js
 */

Output

 (12 + 6) : 11000
 (7 + 18) : 100101
 (45 + 32) : 1110111
 (111 + 132) : 1001000011

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment