Created
March 13, 2016 22:14
-
-
Save sduquej/3f2dcb7915918f887638 to your computer and use it in GitHub Desktop.
Arithmetic operations on numbers represented as strings on javascript
This file contains hidden or 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
/** | |
* Positive addition: both operands are positive | |
*/ | |
function sum(s0, s1) { | |
'use strict'; | |
let result = ''; | |
let carryOver = 0; | |
for(let i = 0, l = Math.max(s0.length, s1.length); i < l; i++) { | |
let sum = carryOver + parseInt(s0.charAt(s0.length - 1 - i ) || 0) + parseInt(s1.charAt(s1.length - 1 - i ) || 0); | |
carryOver = sum > 9 ? 1 : 0; | |
result = String(sum%10).concat(result); | |
} | |
if(carryOver) result = String(carryOver).concat(result); | |
return result; | |
} | |
/** | |
* Single digit multiplication | |
*/ | |
function mulSingleDigit(num, digit) { | |
'use strict'; | |
let result = ''; | |
// carryOver is at most 8 | |
let carryOver = 0; | |
for(let i = 0, l = num.length; i < l; i++) { | |
let mul = carryOver + parseInt(num.charAt(num.length - 1 - i ) || 0) * digit; | |
carryOver = Math.floor(mul/10); | |
result = String(mul%10).concat(result); | |
} | |
if(carryOver) result = String(carryOver).concat(result); | |
return result; | |
} | |
/** | |
* General multiplication of two positive integers | |
*/ | |
function mulIntegers(m1, m2) { | |
'use strict'; | |
let m2Digits = m2.split('').map(Number); | |
let addends = m2Digits.map((d, i) => mulSingleDigit(m1, d).concat('0'.repeat(m2Digits.length - 1 - i))); | |
return addends.reduce((s, e) => sum(s, e), '0'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment