John
John

Reputation: 1118

PHP: Simple recursive function into iterative function

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?

Upvotes: 2

Views: 1043

Answers (2)

xPheRe
xPheRe

Reputation: 2343

If you're looking for a conversion to string for big unsigned integers, the code is actually:

function intToString($myDecimal)
{
    return sprintf('%u', $myDecimal);
}

If you need to do it with iteration:

function intToString($myDecimal)
{
    $result = '';
    while ($myDecimal > 9) {
        $result = ($myDecimal % 10) . $result;
        $myDecimal /= 10;
    }
    return $myDecimal . $result;
}

UPDATE: My bad, digits were inserted in reversed order. Now it should work. Sorry, untested too.

Upvotes: 1

Lekensteyn
Lekensteyn

Reputation: 66405

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 passing 9.99, the output would still be 9.99 because 9.99 < 10.

function intToStringIter($myDecimal){
    $out = "";
    while($myDecimal >= 10) {
        $myDecimal = (int) ($myDecimal / 10);
        $out .= $myDecimal;
    }
    $out .= $myDecimal % 10;
    return $out;
}

Upvotes: 0

Related Questions