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";
?>

Explanation:

  • Function Definition:
    • The test function takes two arguments, $x and $y, and checks the length of the sum of these two numbers compared to the length of $x.
  • Condition:
    • The function converts both the sum of $x and $y and $x individually to strings and compares their lengths.
    • If the length of the sum is greater than the length of $x, it returns $x.
    • Otherwise, it returns the sum of $x and $y.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-53.php