Last active
October 19, 2016 11:07
-
-
Save gskema/3c7dfef1fbfc13972b7e6f98283781d1 to your computer and use it in GitHub Desktop.
Expresses a given decimal number in an arbitrary unique letter base. PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Expresses a given number in a a-z letter base, e.g.: | |
* 0 -> a, 27 -> ba, 932 -> bjw, ... | |
* | |
* @param int $number | |
* | |
* @return string | |
*/ | |
function numberInLetters($number) | |
{ | |
$numberInLetters = ''; | |
// 26 letters a-z | |
$letters = range('a', 'z'); | |
$baseSize = count($letters); | |
// Remainder that we have to express in letters. | |
$remainder = $number; | |
// What's the biggest power of base size that we can use for deducting? | |
$power = $remainder > 0 ? (int)floor(log($remainder, $baseSize)) : 0; | |
while ($power > -1) { | |
// Our current base expressed in numbers | |
$base = (int)pow($baseSize, $power); | |
// How many items of current base can we deduct from the remainder? | |
$items = (int)floor($remainder / $base); | |
// Deduct as many items of base from remainder. | |
$remainder -= ($items * $base); | |
// Append this deducted sum expressed in a letter for this base. | |
$numberInLetters .= $letters[$items]; | |
// Move on to the lower power. | |
$power--; | |
} | |
return $numberInLetters; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment