2

I wrote a program to reverse the number in online compiler. I've checked my code on three online compilers. On writephponline and paiza.io I'm getting correct output, whereas on phpfiddle.org I'm getting some strange answer?

What is it that is producing different Output?

I've used floor function for rounding up the value but that doesn't make any difference I guess.

function reverse($n){
  $count = strlen((string)$n);
  $b=0;
  for($i=0;$i<$count;$i++){
      $a = $n%10;
      $n = floor($n/10);
      $b = ($b+$a)*10;
    }
  return $b/10;
}

echo reverse(123456789);

I expect same answer on all the online compilers but getting different output.

  • 1
    Could you add an example of the differences and what versions they are being run on. – Nigel Ren Sep 11 '19 at 07:22
  • 1
    phpfiddle 7.0.33 paiza.io 7.3.6 writephponline 7.3. I'm getting this - 124696421 in phpfiddle and 54321 in rest 2 after entering 12345 as input – bilal malik Sep 11 '19 at 07:27
  • 1
    Something very strange with the setup on phpfiddle.org. I added some debugs to your code and it seems the modulus operator is returning the wrong values. Your code is correct btw – pinaki Sep 11 '19 at 07:39

2 Answers2

1

I am not sure what is the exact issue with phpfiddle.org, but seems like the % operator is not working correctly there. Changing it to fmod() yields the correct results

<?php

function reverse(int $n){
  $count = strlen((string)$n);
  $b=0;

  for($i=0;$i<$count;$i++){
      $a = fmod($n, 10);
      $n = floor($n/10);
      $b = ($b*10)+$a;
    }
  return $b;
}

echo reverse(123456789);
?>

Update: Figured out the exact issue. phpfiddle is set up on a 32 bit system and is overflowing. This is why fmod() worked. Check similar question @ php modulo return wrong result

pinaki
  • 5,393
  • 2
  • 24
  • 32
1

It's caused by the % which PhpFiddle not do it right. Just leave space before and ater % will make it works well.

<?php
print_r(123456789%10);
echo "\n";
print_r(123456789 % 10);
?>

will output

123456789 9

You can reverse with,

$number = 123456789;
$reverse = join(array_reverse(str_split($number)));
echo $reverse;
LF00
  • 27,015
  • 29
  • 156
  • 295
  • Thanks Kris for answering, I'm aware of array_reverse but I didn't want the solution with predefined function, that's why I'm not marking your answer as correct although it is correct. – bilal malik Sep 11 '19 at 08:21
  • @bilalmalik If you change `$a = $n%10;` to `$a = $n % 10;`, it will works well in phpfiddle, just as I answer shows. – LF00 Sep 11 '19 at 08:27