patterncsharpMinor
Converting to Base 26 in One Based mode
Viewed 0 times
modeonebasedconvertingbase
Problem
I needed to create a simple method that converts numbers in Base 26 (
But that's not all, this Base 26 needs to be One Based. Which means that there is no representation for zero absolute value and there is a representation for 26 absolute value. Let me show a example:
In Base 26 Zero Based the number 18252 will be represented like:
$$
(18252)_{10} = (BBAA)_{26}
$$
where
$$
(18252)_{10} = (ZYZ)_{26}
$$
where
So I came up with this snippet:
Now I wonder if there is a better way write this.
string) using, as expected, letters from a to z.But that's not all, this Base 26 needs to be One Based. Which means that there is no representation for zero absolute value and there is a representation for 26 absolute value. Let me show a example:
In Base 26 Zero Based the number 18252 will be represented like:
$$
(18252)_{10} = (BBAA)_{26}
$$
where
B == 1 and A == 0. But as an One Based I need to get:$$
(18252)_{10} = (ZYZ)_{26}
$$
where
Y == 25 and Z == 26.So I came up with this snippet:
var array = new List();
var div = myNumber;
var getOne = 0;
while (div > 26)
{
var value = div % 26;
value -= getOne;
if (value 0) array.Add(div);
var letters = array.Select(s => (char)('A' + s - 1)).Reverse().ToArray();
return new string(letters);Now I wonder if there is a better way write this.
Solution
You could slightly simplify the code as follows:
Alternatively you can use the
The code:
- Reduce the number of variables.
- Use the
LinkedList(and theAddFirstmethod) instead of theListto eliminate reversion of array.
Alternatively you can use the
List.Insert method to achieve the same result.The code:
private static string ToBase26(int myNumber)
{
var array = new LinkedList();
while (myNumber > 26)
{
int value = myNumber % 26;
if (value == 0)
{
myNumber = myNumber / 26 - 1;
array.AddFirst(26);
}
else
{
myNumber /= 26;
array.AddFirst(value);
}
}
if (myNumber > 0)
{
array.AddFirst(myNumber);
}
return new string(array.Select(s => (char)('A' + s - 1)).ToArray());
}Code Snippets
private static string ToBase26(int myNumber)
{
var array = new LinkedList<int>();
while (myNumber > 26)
{
int value = myNumber % 26;
if (value == 0)
{
myNumber = myNumber / 26 - 1;
array.AddFirst(26);
}
else
{
myNumber /= 26;
array.AddFirst(value);
}
}
if (myNumber > 0)
{
array.AddFirst(myNumber);
}
return new string(array.Select(s => (char)('A' + s - 1)).ToArray());
}Context
StackExchange Code Review Q#90537, answer score: 9
Revisions (0)
No revisions yet.