I posted a question some time ago about an algorithm that generates 6 character base36 strings from integer numbers. It has the restriction that the first and last character must always be a letter and that the whole string is upper case.
Here is the algorithm:
String getId(int id)
{
String s = "";
for(int i = 0; i < 6; i++)
{
int digit;
if((i == 0) || (i == 5))
{
digit = (id % 26) + 10;
id /= 26;
}
else
{
digit = id % 36;
id /= 36;
}
// add the digit to the string:
if(digit < 10)
s = (char)('0' + digit) + s;
else
s = (char)('A' + (digit - 10)) + s;
}
return s;
}
I am trying to create a method that reverses this. I.e. given a String such as A0000K it would return 10. Here is what I have so far:
static int getNumber(String id) {
int base = 36;
int result = 0;
int n = id.length();
for (int i = 0; i < id.length(); i++)
{
n-=1;
int digit = Character.digit(id.charAt(i), base);
if(i == 0 || i == 5) {
result += digit * (Math.pow(base-10, n));
}
else {
result += digit * (Math.pow(base, n));
}
}
return result;
}
I think the issue is around the if statement for calculating result but i'm not too sure how to calculate it. I am basing it of standard algorithms for converting from other bases to base 10.
Can anyone help? Thanks
I'd do something like this, using the assumption that the string is 6 characters long to simplify:
I haven't tested it, but it should work, or at least be pretty close. If you continue having difficulties, try stepping through it in a debugger.