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

后端 未结 5 1388
夕颜
夕颜 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: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".

提交回复
热议问题