Created
September 26, 2018 16:22
-
-
Save belushkin/51db91e185129ac8a17d41d7e372d699 to your computer and use it in GitHub Desktop.
Check if a number is Palindrome, fixed GeeksForGeeks version
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// A recursive PHP program to | |
// check whether a given number | |
// is palindrome or not | |
// A function that reurns true | |
// only if num contains one digit | |
function oneDigit($num) | |
{ | |
// comparison operation is faster | |
// than division operation. So | |
// using following instead of | |
// "return num / 10 == 0;" | |
return (($num >= 0) && | |
($num < 10)); | |
} | |
// A recursive function to find | |
// out whether num is palindrome | |
// or not. Initially, dupNum | |
// contains address of a copy of num. | |
function isPalUtil($num, &$dupNum) | |
{ | |
// Base case (needed for recursion | |
// termination): This statement | |
// mainly compares the first digit | |
// with the last digit | |
if (oneDigit($num)) { | |
return ($num == ($dupNum) % 10); | |
} | |
// This is the key line in this | |
// method. Note that all recursive | |
// calls have a separate copy of | |
// num, but they all share same | |
// copy of *dupNum. We divide num | |
// while moving up the recursion tree | |
if (!isPalUtil((int)($num / 10), $dupNum)) { | |
$dupNum = false; | |
return false; | |
} | |
if ($dupNum === false) { | |
return false; | |
} | |
// The following statements are | |
// executed when we move up the | |
// recursion call tree | |
$dupNum = (int)($dupNum / 10); | |
// At this point, if num%10 | |
// contains i'th digit from | |
// beiginning, then (*dupNum)%10 | |
// contains i'th digit from end | |
return ($num % 10 == ($dupNum) % 10); | |
} | |
// The main function that uses | |
// recursive function isPalUtil() | |
// to find out whether num is | |
// palindrome or not | |
function isPal($num) | |
{ | |
// If num is negative, | |
// make it positive | |
if ($num < 0) | |
$num = (-$num); | |
// Create a separate copy of | |
// num, so that modifications | |
// made to address dupNum | |
// don't change the input number. | |
$dupNum = ($num); // *dupNum = num | |
return isPalUtil($num, $dupNum); | |
} | |
// Driver Code | |
$n = 1234321; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment