PHP: How to output list like this: AA, AB, AC, all the way to ZZZY, ZZZZ, ZZZZA etc

后端 未结 5 1380
夕颜
夕颜 2020-12-10 18:56

I\'m trying to write a function that\'ll convert an integer to a string like this, but I can\'t figure out the logic... :(

1 = a
5 = e
27 = aa
28 = ab
etc...         


        
相关标签:
5条回答
  • 2020-12-10 19:04

    Long list of them here:

    /*
     * Convert an integer to a string of uppercase letters (A-Z, AA-ZZ, AAA-ZZZ, etc.)
     */
    function num2alpha($n)
    {
        for($r = ""; $n >= 0; $n = intval($n / 26) - 1)
            $r = chr($n%26 + 0x41) . $r;
        return $r;
    }
    
    /*
     * Convert a string of uppercase letters to an integer.
     */
    function alpha2num($a)
    {
        $l = strlen($a);
        $n = 0;
        for($i = 0; $i < $l; $i++)
            $n = $n*26 + ord($a[$i]) - 0x40;
        return $n-1;
    }
    
    0 讨论(0)
  • 2020-12-10 19:11

    You will have to use base_convert to convert your numbers to a 26 base:

    base_convert(35, 10, 26);
    

    That gives you the individual components in numbers from 1 - p, so 35 becomes 19 (1 * 26 + 9). Then you have to map the individual components to your desired set, so 1 => a, 9 => i, a => j, etc. and 19 becomes ai.

    0 讨论(0)
  • 2020-12-10 19:18

    I'll add this answer to sum up the comments regarding the misuse of base-26.

    A common first reaction when confronted with this problem is to think "There are 26 letters, so this must be base-26! All I need to do is map each letter to its corresponding number".

    But this is not base-26. It's easy to see why: there is no zero!

    In base-26, the number twenty-six is the first number with two digits, and is written "10". In this counting system, twenty-six has a single digit, "Z", and the first two-digit number is twenty-seven.

    But what if we make A=0, ..., Z=25? This way we have a zero and the first two-digit number becomes twenty-six. So far so good. How do we write twenty-six now? That's "AA". But... isn't A=0? Ooops! A = AA = AAA = "0" = "00" = "000".

    0 讨论(0)
  • 2020-12-10 19:23
    void convert(int number)
    {
    
            string str = "";
    
        while(number)
        {
            char ch;
            ch = (number - 1) % 26 + 65;    
            str = ch + str;
            number = (number-1) / 26;
        }
    
        cout << str << endl;
    }
    
    0 讨论(0)
  • Well, you're pretty much converting from base 10 to base 26. Base 10 has digits 0-9, whereas base 26 can be expressed with "digits" A-Z. Conversion from base-10 is easy - see e.g. this: http://www.mathsisfun.com/base-conversion-method.html Edit: actually, base-26 fails to account for multiple equivalent ways to write 0 ( 0 = 00 = 000).

    0 讨论(0)
提交回复
热议问题