Why won't this palindrome code run

Discussion in 'PHP' started by Ipodman79, Feb 10, 2014.

  1. #1
    This is my code,

    
    $num = 37;
    $rev = 0;
    $times = 0;
    
    while ($num != $rev){
     if ($num == $rev){
     echo $num . ' ' . $times;
     }
     else
     {
      $rev=($rev *10)+($num % 10);
      $num=(int)($num / 10 );
      $times++; 
    }
    }
    
    PHP:
    I want it to get a number, $num, and then reverse it. I then want to add the numbers together. I want to keep doing this until I get a palindrome number.

    The output should print out, the palindrome number and the number of times, $times, it took to get it separated by a space.

    Thanks
     
    Solved! View solution.
    Ipodman79, Feb 10, 2014 IP
  2. #2
    <?php
    $maxTries = 255; //in case this results in a long-running loop
    
    $number = 37;
    
    $string = '';
    $reverse = 0;
    $tries = 0;
    $found = false;
    
    do {
    $string = strval($number);
    $reverse = strrev($string);
    $reverse = intval($reverse);
    
    if($number===$reverse)
      $found = true;
    else {
      ++$tries;
      $number += $reverse;
    }
    } while($tries<$maxTries && !$found);
    
    if($found)
    echo $number,' ',$tries;
    else
    echo 'Try limit exceeded.';
    Code (markup):
    It should work, but I haven't tested it.
     
    xtmx, Feb 10, 2014 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #3
    while ($num != $rev){
     if ($num == $rev){
    Code (markup):
    do we see a problem here?!?
     
    deathshadow, Feb 12, 2014 IP
    xtmx likes this.
  4. xtmx

    xtmx Active Member

    Messages:
    359
    Likes Received:
    12
    Best Answers:
    4
    Trophy Points:
    88
    #4
    I was so focused on the bottom part being wrong, I didn't even notice that!
     
    xtmx, Feb 12, 2014 IP