Amazon Interview Question
Software Engineer / Developerstemp=temp1=n;
while(temp>0) // Find no of characters string will contain
{
no_of_char++;
temp=temp-pow(26,no_of_char);
}
str = (char *)malloc(no_of_char+1);// Dynanically Allocate the buffer
while(temp1>0)
{
temp= temp1 %26; // To find no with respect to alphabet
if(temp!=0)
str[next_char_index++]=temp+65-1;
else
{ // When modulas = 0 we know it is Z(since 26)
str[next_char_index++]='Z';
temp1--;
}
temp1= temp1/(26); // divide by 26 for next pass
}
str[next_char_index]='\0'; // Terminate string with NULL character
strrev(str); // since the characters are stored in reverse manner
#include <stdio.h>
int main(){
int rownum = 2842 ;
int i = rownum ;
int j = i ;
int count = 0 ;
int power = 0 ;
while(i >=26){
j = i ;
count = 0 ;
power = 1 ;
while(j >=26){
count++ ;
j = j/26 ;
}
printf("%c", 'A'+ j - 1) ;
for(j = 1 ; j <= count; j++){
power = power*26 ;
}
i = (i % power) ;
}
printf("%c\n", ('A' + i)) ;
return 0 ;
}
public void printSeries(int n) {
int qt = n / 26;
qt--;
int rem = n % 26;
rem--;
char[] alpha = new char[26];
char a = 'A';
for (int i = 0; i < 26; i++) {
alpha[i] = (char) a;
a++;
}
String out = "";
if (rem == -1) {
qt--;
rem = 25;
}
if (qt >= 0) {
out = out + alpha[qt];
}
if (rem >= 0) {
out = out + alpha[rem];
}
System.out.println(qt + " " + rem);
System.out.println(out);
}
Simply convert 'n' to a base-26 number. Each digit maps to a letter.
- Johnny April 23, 2010void f(int n)
{
if(n == 0)
return;
f((n-1)/26);
printf("%c", ((n-1)%26+'A'));
}