Wednesday, April 13, 2011

Converting Alphabet to Decimal

Question: Convert Alphabet to Decimal Number. For example, numbering column numbers  in MS Excel;
   A → 1,
   Z → 26,
   AA → 27,
   ZBC → 17631.


When considering only capitals, following Java function converts alphabet to decimal.

public int alphaToDecimal(char input[]) {
int ret = 0;
int a, b;
int i, j;
for (i=0; i<input.length; i++) {
a = input[i] - 'A' + 1;
b = 1;
                // you can use Math.pow(); 
for(j=0; j<input.length-i-1;j++)
b *= 'Z'-'A' + 1;
ret += a*b;
}
return ret;
}

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Macys Printable Coupons