Hi there,
I am going to show , How to reverse number using php.
Reverse number using without php function:
Example:
Input number is: 12345
Reverse number will be: 54321
Logic:
//input
$num = 12345;
//reverse should be 0
$reverse = 0;
//run loop until num is not zero
while ($num != 0)
{
$reverse = $reverse * 10 + $num % 10;
$num = (int)($num / 10);
}
/printing the reverse number
echo "Reverse number of 12345 is: $reverse";
?>
Output: Reverse number of 12345 is: 54321
Reverse number Program in PHP:
<?php
function reverse_number($number)
{
/* Typecast the number into string. */
$snum = (string) $number;
/* Reverse the string. */
$revstr = strrev($snum);
/* Typecast string into int. */
$reverse = (int) $revstr;
return $reverse;
}
echo "Reverse number of 12345 is:".reverse_number(12345);
?>
Output: Reverse number of 12345 is: 54321
Happy coding!
I am going to show , How to reverse number using php.
Reverse number using without php function:
Example:
Input number is: 12345
Reverse number will be: 54321
Logic:
- Let's Take a number12345.
- Assign 0 to the variable, in which we are going to store reverse number
- Run the following two steps until number is not zero
- Get the digit using modules (%) operator and add it into the ‘reverse*10’
- Now, divide the number by 10
- Finally, when number will be zero, print the ‘reverse’
//input
$num = 12345;
//reverse should be 0
$reverse = 0;
//run loop until num is not zero
while ($num != 0)
{
$reverse = $reverse * 10 + $num % 10;
$num = (int)($num / 10);
}
/printing the reverse number
echo "Reverse number of 12345 is: $reverse";
?>
Output: Reverse number of 12345 is: 54321
Reverse number Program in PHP:
<?php
function reverse_number($number)
{
/* Typecast the number into string. */
$snum = (string) $number;
/* Reverse the string. */
$revstr = strrev($snum);
/* Typecast string into int. */
$reverse = (int) $revstr;
return $reverse;
}
echo "Reverse number of 12345 is:".reverse_number(12345);
?>
Output: Reverse number of 12345 is: 54321
Happy coding!
Good..
ReplyDelete