w3resource

PHP Exercises: Check if two given non-negative integers have the same last digit


23. Same Last Digit Check

Write a PHP program to check if two given non-negative integers have the same last digit.

Sample Solution:

PHP Code :

<?php
// Define a function that checks if the last digits of two numbers have the same absolute value
function test($x, $y) 
{
    // Check if the absolute value of the last digit of both numbers is the same
    return abs($x % 10) == abs($y % 10);
}

// Test the function with different number pairs
var_dump(test(123, 456));
var_dump(test(12, 512));
var_dump(test(7, 87));
var_dump(test(12, 45));
?>

Explanation:

  • Function Definition:
    • The test function takes two integer parameters $x and $y and checks if their last digits have the same absolute value.
  • Last Digit Comparison:
    • The last digit of each number is obtained using the modulus operator (% 10), which provides the remainder when divided by 10.
    • The abs function ensures that the comparison is based on the absolute value of the last digits (to handle negative numbers).
    • It then checks if the last digits are the same and returns true if they are; otherwise, it returns false.

Output:

bool(false)
bool(true)
bool(true)
bool(false)

Visual Presentation:

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

Flowchart:

Flowchart: Check if two given non-negative integers have the same last digit.

For more Practice: Solve these Related Problems:

  • Write a PHP script to check if two non-negative integers share the same rightmost digit using modulo arithmetic.
  • Write a PHP function to compare the last digit of two numbers and return a boolean result.
  • Write a PHP program to extract and compare the units place of two integers with built-in string functions as an alternative approach.
  • Write a PHP script to verify whether the final digit of two given numbers is identical by converting numbers to strings.

Go to:


PREV : Count 'z' Characters Between 2 and 4.
NEXT : Uppercase Last 3 Characters of String.

PHP Code Editor:



Contribute your code and comments through Disqus.

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.