Interview Questions

256.Excel labels its rows with letters.....

Microsoft Interview Questions and Answers


(Continued from previous question...)

256.Excel labels its rows with letters.....

Question:
Excel labels its rows with letters. For example row 0 is labeled 'A', row 1 is labeled 'B', row 26 is labeled 'AA', and so on.

Design, and implement in C, an algorithm that will map any row number, such as 2842, into into its proper row designation. For instance row 2842, maps to the designation 'DEI'


maybe an answer:


Get the length in final array / string.
If number is some power of 26 - 1, pad Z's
else use modulus and division approach by subtracting modulus from number. and fill out characters from array into final array
Print final array in reverse.

The code itself is very clear

public static void GetExcelLabel(int n)
{
int length = 0;
int temp = n;
int i;
int mod;
char[] arr = new Char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

StringBuilder strRet = new StringBuilder();
//Find the length of final string
while (temp > 0)
{
length++;
temp /= 26;
}

//Paddig is done (To work for cases like Z, ZZ, ZZZ, ZZZZ i.e. 26-1, 26^2-1, ....)
temp = n + 1;
if (temp == Math.Pow(26, length))
{
for (i = 0; i < length; i++)
strRet.Append("Z");
}
else
{
while (length > 1)
{
mod = n % 26;
strRet.Append(arr[mod]);
n = n - mod;
n = n / 26;
length--;
}
strRet.Append(arr[n - 1]);
}
//Print array in reverse
char[] charArr = strRet.ToString().ToCharArray();
Array.Reverse(charArr);
Console.Out.WriteLine(new String(charArr));
}

(Continued on next question...)

Other Interview Questions