PHP Exercises: Check if two or more non-negative given integers have the same rightmost digit
PHP Basic Algorithm: Exercise-49 with Solution
Write a PHP program to check if two or more non-negative given integers have the same rightmost digit.
Sample Solution:
PHP Code :
<?php
// Define a function that checks if the last digit of $x, $y, or $z is the same
function test($x, $y, $z)
{
// Check if the last digit of $x is equal to the last digit of $y or $z,
// or if the last digit of $y is equal to the last digit of $z
return $x % 10 == $y % 10 || $x % 10 == $z % 10 || $y % 10 == $z % 10;
}
// Test the function with different sets of numbers
var_dump(test(11, 21, 31))."\n";
var_dump(test(11, 22, 31))."\n";
var_dump(test(11, 22, 33))."\n";
?>
Explanation:
- Function Definition:
- The function test checks if any two of the numbers $x, $y, or $z have the same last digit.
- Condition Checked:
- The function calculates the last digit of each number using the modulo operation (% 10).
- It then checks:
- If the last digit of $x is equal to the last digit of $y or $z.
- Or if the last digit of $y is equal to the last digit of $z.
Output:
bool(true) bool(true) bool(false)
Visual Presentation:
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to check if three given numbers are in strict increasing order, such as 4 7 15, or 45, 56, 67, but not 4 ,5, 8 or 6, 6, 8.However,if a fourth parameter is true, equality is allowed, such as 6, 6, 8 or 7, 7, 7.
Next: Write a PHP program to check three given integers and return true if one of them is 20 or more less than one of the others.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-49.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics