数字到唯一字符组合


Number to unique character combination

我想在PHP中为从1到无穷大的每个数字创建一个字符组合。

允许的字符是a-z

  • 0->a
  • 1->b
  • 2->c
  • 25->z
  • 26->aa
  • 27->ab

我希望你明白我的意思。非常感谢。

内联添加了所有注释。

//Your number
$num = 700;
//Stores the result
$result = "";
$count = 0;
while ($num>=1)
{
    /*If we don't do the following line,
    26 will be "ba" but not "aa"
    As a number 2 can be written as 02 in decimal, but in your example we can't do that, as you won't allow writing 02 as "ac", but simply "c".*/
    if ($num < 26) $offset=9; else $offset=10;
    //The following part is just a simple base conversion
    $remainder = $num%26;
    $digit =  base_convert($remainder+$offset,10,36);
    $result .= $digit;
    $num = floor($num/26);
    $count++;
}
//Display in reverse order
$result = strrev($result);
echo $result;