Skip to content

Instantly share code, notes, and snippets.

@allucardster
Last active January 22, 2020 05:51
Show Gist options
  • Save allucardster/3020ee0365ac2c7258ebb5cab860009f to your computer and use it in GitHub Desktop.
Save allucardster/3020ee0365ac2c7258ebb5cab860009f to your computer and use it in GitHub Desktop.
<?php
/*
Find the number of carry operations when sum two numbers. For example
the carry operations for 66+75 is 2 because:
11
66
+75
–––
141
6+5 = 11, then have 1 and carry 1 (first carry operation)
6+7+1 = 14, then have 4 and carry 1 (second carry operation)
1+0 = 1, then have 1 and carry none
*/
function numberOfCarryOperations(int $a, int $b) : int
{
$arr = array_reverse(array_map('intval', str_split((string) $a)));
$brr = array_reverse(array_map('intval', str_split((string) $b)));
$len = count($arr) > count($brr) ? count($arr) : count($brr);
$crr = 0;
$num = 0;
for($i = 0; $i < $len; $i++) {
$aDgt = isset($arr[$i]) ? $arr[$i] : 0;
$bDgt = isset($brr[$i]) ? $brr[$i] : 0;
$sum = $aDgt + $bDgt + $crr;
if ($sum >= 10) {
$strSum = (string) $sum;
$num++;
$crr = intval($strSum[0]);
} else {
$crr = 0;
}
}
return $num;
}
$test = [
[66, 75], // 2
[123, 456], // 0
[555, 555], // 3
[900, 11], // 0
[145, 55], // 2
[0, 0], // 0
[1, 99999], // 5
[999045, 1055], // 5
[101, 809], // 1
[189, 209], // 1
];
foreach ($test as $params) {
var_dump(numberOfCarryOperations(...$params));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment