Last active
November 14, 2021 00:09
-
-
Save DimitrK/9cbc13289bd230616f5516435d80fb1a to your computer and use it in GitHub Desktop.
Counts the number of carry operation in an addition of two numbers
This file contains 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
function numberOfCarryOperations(x,y) { | |
var xs = x.toString(); | |
var ys = y.toString(); | |
var cary = 0; | |
var operations=0; | |
var xCurrent; | |
var yCurrent; | |
while (xs.substr(xs.length-1) || ys.substr(ys.length-1) ) { | |
yCurrent =ys.substr(ys.length-1); | |
xCurrent = xs.substr(xs.length-1); | |
xs = xs.substr(0, xs.length-1); | |
ys = ys.substr(0, ys.length-1); | |
var sum = cary + Number(yCurrent) + Number(xCurrent); | |
if ( sum >= 10) { | |
cary = Math.floor(sum/10); | |
operations += 1; | |
} | |
} | |
return operations; | |
} |
This file contains 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
console.log(numberOfCarryOperations(123, 456) === 0) | |
console.log(numberOfCarryOperations(555, 555) === 3) | |
console.log(numberOfCarryOperations(900, 11) === 0) | |
console.log(numberOfCarryOperations(145, 55) === 2) | |
console.log(numberOfCarryOperations(0, 0) === 0 ) | |
console.log(numberOfCarryOperations(1, 99999) === 5) | |
console.log(numberOfCarryOperations(999045, 1055) === 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Counts the number of carry operation in an addition of two numbers