Pacerier
Pacerier

Reputation: 89593

Why does my php code loop infinitely?

I have a function GetLetters that returns

  1. a when I give it 1

  2. b when I give it 2

  3. z when I give it 26

  4. aa when I give it 27

  5. ab when I give it 28

Basically you'd get the idea, this is my solution however it is looping indefinitely when I supply any input value above 26, does anyone know what's wrong with it ?

function GetLetter($amt){
    if($amt<=26){
        return strtolower(chr(64+$amt));
    }
    $letters=array();
    while(true){
        $quotient=$amt%26;
        array_unshift($letters,GetLetter($quotient===0?26:$quotient));
        $amt=floor(($amt-1)/26);
        if($amt===0){
            break;
        }
    }
    return implode("",$letters);
}

Upvotes: 0

Views: 120

Answers (4)

Lubulos
Lubulos

Reputation: 290

Whenever you use a repetition statement like the while statement you shouldn't utilize float type to determine the end of the repetition. Floating-point numbers are never perfectly precise, so they aren't the ideal for condition statements.

Upvotes: 1

CodeCaster
CodeCaster

Reputation: 151588

See here, you're comparing floats. Try intval().

So change

if($amt===0){

to

if(intval($amt)==0){

Upvotes: 4

NikiC
NikiC

Reputation: 101906

Just as an alternative way to do it (note though that it is O(n)):

function getLetters($n) {
    for ($chr = 'a'; --$n;) ++$chr;
    return $chr;
}

(If you increment a character in PHP it'll first go from a..z, then aa..zz and so on, just as you want.)

Upvotes: 2

a1ex07
a1ex07

Reputation: 37354

I think floor returns float, and you use ===, not == for comparing with integer(0), so float(0) === int(0) always false.

Upvotes: 3

Related Questions