Popular Posts

Tuesday, February 8, 2011

Excel sheet question

Q:Given a series A,B,C .......Z, AA, AB,AC,AD....AZ,BA,BB...BZ,CA....(Open excel sheet. The names of column represent the series). Given input as number 'n'. Output the 'n' th string of the series. & also vice versa if given string prints its corrsponding string...e.g given AC then its interger is 29 & given 40774 its string value is ABZ..


Sol :base 26 conversion with digits being A-Z

Code :
public static String ExcelMapIntToStr(int n)
{
StringBuilder sb = new StringBuilder();
while(n>0)
{
sb.append((char)(('A' - 1) + (n-1)%26 + 1));
n = (n-1)/26;
}
return sb.reverse().toString();
}

public static int ExcelMapStrToInt(String str)
{
int val = 0;
int base = 1;
for(int i = str.length() - 1; i>=0; i--)
{
val += (str.charAt(i) - ('A' - 1))*base;
base *= 26;
}
return val;
}


Refer : http://geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-fresher-about-algorithms-data-structure-strings

No comments:

Post a Comment