w3resource

PHP Exercises: Compute the sum of two given non-negative integers x and y as long as the sum has the same number of digits as x

PHP Basic Algorithm: Exercise-53 with Solution

Write a PHP program to compute the sum of two given non-negative integers x and y as long as the sum has the same number of digits as x. If the sum has more digits than x then return x without y.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that compares the length of the sum of two numbers with the length of the first number
// If the sum has a greater length, return the first number; otherwise, return the sum
function test($x, $y)
{
    // Check if the length of the sum of $x and $y is greater than the length of $x
    // If true, return $x; otherwise, return the sum of $x and $y
    return strlen((string)($x + $y)) > strlen((string)$x) ? $x : $x + $y;
}

// Test the 'test' function with different input values and display the results
echo (test(4, 5))."\n";
echo (test(7, 4))."\n";
echo (test(10, 10))."\n";
?>

Sample Output:

9
7
20

Flowchart:

Flowchart: Compute the sum of two given non-negative integers x and y as long as the sum has the same number of digits as x.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to check two given integers, each in the range 10..99. Return true if a digit appears in both numbers, such as the 3 in 13 and 33.
Next: Write a PHP program to compute the sum of three given integers. If the two values are same return the third value.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.