Skip to content

Instantly share code, notes, and snippets.

@lbvf50mobile
Last active October 8, 2020 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lbvf50mobile/34cd996cb277f0639c152a38a8bdb461 to your computer and use it in GitHub Desktop.
Save lbvf50mobile/34cd996cb277f0639c152a38a8bdb461 to your computer and use it in GitHub Desktop.
Just PHP FUN 123.
<?php
# https://www.codewars.com/kata/5324945e2ece5e1f32000370 Sum Strings as Numbers.
function sum_strings($a, $b) {
return $a + $b;
}
# -----------------------------------------------------------------------------
function sum_strings($a, $b) {
$max = max(strlen($a),strlen($b));
/*echo "Start. $max; \n";
echo "$a \n";
echo "$b \n";*/
$a = to_a($a,$max);
$b = to_a($b,$max);
$ans = "";
$nxt = 0;
for($i = 0; $i < $max; $i += 1){
$tmp = intval($a[$i]) + intval($b[$i]) + $nxt;
$nxt = $tmp >= 10 ? 1 : 0;
$ans = strval($tmp%10).$ans;
}
if(1 == $nxt) $ans = "1".$ans;
if(1 < strlen($ans)) $ans = preg_replace('/^0+/',"",$ans);
//echo "$ans \n";
return $ans;
}
function to_a($str,$max){
$padd = str_pad($str,$max,"0",STR_PAD_LEFT);
return array_reverse(str_split($padd));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment