Last active
January 22, 2020 05:51
-
-
Save allucardster/3020ee0365ac2c7258ebb5cab860009f to your computer and use it in GitHub Desktop.
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
<?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