w3resource

PHP Exercises: Check if two or more non-negative given integers have the same rightmost digit


49. Same Rightmost Digit Among Integers

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:

PHP Basic Algorithm Exercises: Check if two or more non-negative given integers have the same rightmost digit.

Flowchart:

Flowchart: Check if two or more non-negative given integers have the same rightmost digit.

For more Practice: Solve these Related Problems:

  • Write a PHP script to test if two or more non-negative integers share the same last digit using modulo operations.
  • Write a PHP function to iterate through a variable list of numbers and check if they all end with the same digit.
  • Write a PHP program to extract the last digit of each number in an array and compare them for uniformity.
  • Write a PHP script to implement a comparison that returns true only if every integer in a given list has the same units place digit.

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.



Follow us on Facebook and Twitter for latest update.