📜  编写一个程序来显示PHP中任意数字的倒数?

📅  最后修改于: 2022-05-13 01:56:54.716000             🧑  作者: Mango

编写一个程序来显示PHP中任意数字的倒数?

编写一个程序来反转整数的数字。

例子 :

Input : num = 12345
Output: 54321

Input : num = 876
Output: 678

可以使用迭代方式递归方式来实现

迭代方法:

算法:

Input:  num
(1) Initialize rev_num = 0
(2) Loop while num > 0
    (a) Multiply rev_num by 10 and add remainder
        of num divide by 10 to rev_num
        rev_num = rev_num*10 + num%10;
    (b) Divide num by 10
(3) Return rev_num

例子:

程序:

PHP
 1) {
        $rev_num = $rev_num * 10 + $num % 10;
        $num = (int)$num / 10;
    }
    return $rev_num;
}
  
// Driver Code
$num = 456213;
echo "Original number is :".$num;
echo "\r\n";
echo "Reverse of no. is ", reversDigits($num);
?>


PHP
 0) {
        reversDigits((int)($num / 10));
        $rev_num += ($num % 10) *
                    $base_pos;
        $base_pos *= 10;
    }
    return $rev_num;
}
  
// Driver Code
$num = 456213;
echo "Original number is :".$num;
echo "\r\n";
echo "Reverse of no. is ",
    reversDigits($num);
  
?>


输出
Original number is :456213
Reverse of no. is 312654

时间复杂度: O(log(n)),其中 n 是输入数。

辅助空间: O(1)

递归方法:

PHP

 0) {
        reversDigits((int)($num / 10));
        $rev_num += ($num % 10) *
                    $base_pos;
        $base_pos *= 10;
    }
    return $rev_num;
}
  
// Driver Code
$num = 456213;
echo "Original number is :".$num;
echo "\r\n";
echo "Reverse of no. is ",
    reversDigits($num);
  
?>
输出
Original number is :456213
Reverse of no. is 312654

时间复杂度: O(log(n)),其中 n 是输入数。