fork download
  1. <?php
  2. function compute($a, $b) {
  3. if($b > $a) {
  4. $c = $a;
  5. $a = $b;
  6. $b = $c;
  7. }
  8. $s = str_split($a);
  9. $s2 = str_split($b);
  10. $r = 0;
  11. $lr = 0;
  12. $temp = 0;
  13. $value = "";
  14. $j = count($s2) - 1;
  15. for($i = (count($s) - 1); $i >= 0; $i--) {
  16. if($j >= 0) {
  17. $temp = $s[$i] + $s2[$j] + $lr;
  18. if($temp > 9) {
  19. $value .= substr($temp, -1);
  20. $lr = substr($temp, 0, -1);
  21. $r++;
  22. }
  23. else {
  24. $value .= $temp;
  25. }
  26. $j--;
  27. }
  28. else {
  29. $temp = $s[$i] + $lr;
  30. if($temp > 9) {
  31. $value .= substr($temp, -1);
  32. $lr = substr($temp, 0, -1);
  33. $r++;
  34. }
  35. else {
  36. $value .= $temp;
  37. }
  38. }
  39. }
  40. if($lr != 0) { $value .= $lr; if($r > 1) { --$r; } }
  41. return "The sum of ".$a." and ".$b." is ".strrev($value)." and the carry out used to obtain this result is ".$r."\n";
  42. }
  43. echo compute(999, 1);
  44. echo compute(1, 999);
  45. echo compute(700, 9);
  46. echo compute(987654321, 123456789);
  47. echo compute(9, 9);
  48. echo compute(9, 7);
  49. echo compute(9, 1);
  50. echo compute(20, 20);
  51. ?>
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
The sum of 999 and 1 is 1000 and the carry out used to obtain this result is 2
The sum of 999 and 1 is 1000 and the carry out used to obtain this result is 2
The sum of 700 and 9 is 709 and the carry out used to obtain this result is 0
The sum of 987654321 and 123456789 is 1111111110 and the carry out used to obtain this result is 8
The sum of 9 and 9 is 18 and the carry out used to obtain this result is 1
The sum of 9 and 7 is 16 and the carry out used to obtain this result is 1
The sum of 9 and 1 is 10 and the carry out used to obtain this result is 1
The sum of 20 and 20 is 40 and the carry out used to obtain this result is 0