PHP Exercises: 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
PHP Basic Algorithm: Exercise-52 with Solution
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.
Sample Solution:
PHP Code :
<?php
// Define a function named 'test' that checks if the digits of two numbers have any common digit
function test($x, $y)
{
// Check if the tens digit of $x is equal to the tens digit of $y or if the tens digit of $x is equal to the units digit of $y
// or if the units digit of $x is equal to the tens digit of $y or if the units digit of $x is equal to the units digit of $y
return $x / 10 == $y / 10 || $x / 10 == $y % 10 || $x % 10 == $y / 10 || $x % 10 == $y % 10;
}
// Test the 'test' function with different input values and display the results
var_dump(test(11, 21))."\n";
var_dump(test(11, 20))."\n";
var_dump(test(10, 10))."\n";
?>
Explanation:
- Function Definition:
- The test function checks if two numbers, $x and $y, have any common digit.
- Conditions:
- The function compares the digits of $x and $y by splitting them into tens and units places.
- Specifically, it checks if:
- The tens digit of $x is equal to the tens digit of $y.
- The tens digit of $x is equal to the units digit of $y.
- The units digit of $x is equal to the tens digit of $y.
- The units digit of $x is equal to the units digit of $y.
- If any of these conditions are met, it returns true; otherwise, it returns false.
Output:
bool(true) bool(false) bool(true)
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to find the larger from two given integers. However if the two integers have the same remainder when divided by 7, then the return the smaller integer. If the two integers are the same, return 0.
Next: 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.
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-52.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics