PHP:简单的递归函数变成迭代函数
我本来打算用 C 语言来做这件事,但很困惑,所以我转向 PHP,并且能够复制一个递归函数来做到这一点。我正在用数学将整数转换为字符串。就是这样:
function intToString($myDecimal){
if($myDecimal < 10) {
return $myDecimal;
}
return intToString(($myDecimal / 10)) . ($myDecimal % 10);
}
我之前能够转换递归阶乘函数..但是我没有任何线索..我的尝试如下:
function intToStringIter($myDecimal){
$out = "";
while($myDecimal > 10) {
$myDecimal /= 10;
$out .= $myDecimal;
}
$out .= $myDecimal % 10;
return $out;
}
我想我现在太累了,无法看到正确的逻辑..它返回22而不是20,我无法理解什么是正确的。你看到我做错了什么了吗?
I was going to do it in C but was confused, so I turned to PHP and was able to copy a recursive function to do this. I am converting an integer into a string with math. Here it is:
function intToString($myDecimal){
if($myDecimal < 10) {
return $myDecimal;
}
return intToString(($myDecimal / 10)) . ($myDecimal % 10);
}
I was able to convert a recursive factorial function before.. but with this I just have no clue.. My attempt is as follows:
function intToStringIter($myDecimal){
$out = "";
while($myDecimal > 10) {
$myDecimal /= 10;
$out .= $myDecimal;
}
$out .= $myDecimal % 10;
return $out;
}
I think I am too tired to see the proper logic at the moment.. It returns 22 instead of 20, I cannot wrap my head around what is correct. Do you see what I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您正在寻找大无符号整数到字符串的转换,则代码实际上是:
如果您需要通过迭代来完成此操作:
更新:我的错,数字以相反的顺序插入。现在应该可以了。抱歉,也未经测试。
If you're looking for a conversion to string for big unsigned integers, the code is actually:
If you need to do it with iteration:
UPDATE: My bad, digits were inserted in reversed order. Now it should work. Sorry, untested too.
PHP 对变量的要求不是很严格。如果情况愿意,整数将变成浮点数。在您的代码中,
$myDecimal /= 10
可以生成$myDecimal
的浮点数。以下强制 $myDecimal 保持整数。注意:您应该仅传递整数,如果您传递9.99
,输出仍将为9.99
,因为9.99
9.99
9.99
9.99
9.99
9.99
9.99
9.99 10.
.PHP is not very strict with variables. An integer will become an float if the situation likes it. In your code,
$myDecimal /= 10
could make a float of$myDecimal
. The following forces $myDecimal to stay an integer. Note: you should pass only integers, if you're passing9.99
, the output would still be9.99
because9.99 < 10
.