I'm trying to wri开发者_Python百科te 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...
Can anyone help? I'm really niffed that I can't wrap my head around how to write this... :(
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;
}
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".
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
.
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).
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;
}
精彩评论