Microsoft Interview Question for Software Engineer in Tests


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
15
of 17 vote

Base 26 representation from 1 to 26.

void print(int n)
{
	if(n>0)
	{
		n--;
		print(n/26);
		printf("%c",(n%26)+65);
	}
}

- Aashish July 12, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Cool..works great :). Can u tell me the significance of "n--" here? Why is it used? I don't get it.

- Kiran Kumar August 07, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

The base representation starts from 0. Here it will be given from 1.
So, n--.

- Aashish August 07, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Thank u :)

- Kiran Kumar August 07, 2012 | Flag
Comment hidden because of low score. Click to expand.
Comment hidden because of low score. Click to expand.
0
of 0 votes

@ Nasser Ghazali, the code is fine. You can check the output here: ideone.com/fZ8LE
Regarding direction of output, check against input 52

- Aashish September 02, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

why +65?

- ruth542 March 14, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Elegant solution

- Aleksey.M May 27, 2013 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

This code is incorrect. You have to use while loop, not an if condition. The idea is right though. The correct code:

void print(int n)
{
while(n>0)
{
n--;
print(n/26);
printf("%c",(n%26)+65);
}
}

- Diptesh Chatterjee February 16, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 3 vote

nerd's solution is almost correct, just need to take care of some offset

template<class T>
string Translate(T input) {
  static const char kLookUp[26] = {'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'};
  string res = "";
  while (input > 0) {
    T idx = (input - 1) % 26;
    res = kLookUp[idx] + res;
    input = (input - 1) / 26;
  }
  return res;
}

- airfang613 July 10, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

hey can you please explain how the following requirement is met in ur code....

"One additional consideration here is, the user is free to provide any length of integer (bigint long int etc), no restriction there."

is template has any role in that???

- student July 10, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

as I understand the question, the function just need to be able to take different types of input, unless there's some other interpretation?

- airfang613 July 11, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

is my code fits to this problem

void encrypt(int n)
{
	int r,q=n;
	char *res="";
	while(q>0){
		r=q%26;
		if(r==0){
			q=q-1;
			r=26;
		}
		if(r>0 && r<=26){
			res=appendAtLeft(res,r);
			if(q>0){
				q=q/26;	
			}
		}
	}
	printf("%s\n",res);
}

- zubair alam July 13, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@ airfang613 : Excellent !!! It works perfectly with below changes :

int idx = (input - 1) % 26;

instead of

T idx = (input - 1) % 26;

Also there is not constructor which convert char to string, so you need to create char [26][2] array with string like "A\0", "B\0"...etc

There is no constructor available which will change char to string.so below statement need to modify :

res = kLookUp[idx] + res;

as

res.insert(res.begin(), kLookUp[idx]);

- Sach July 14, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Btw, the team I interviewed with uses C/C++ predominantly hence I mentioned in the beginning to write a code in C.

- jeanclaude July 09, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Convert the decimal Base Number to 26 Base Number whose digits are A-Z

- nerd July 09, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

charLookup[] = {'A','B','C'.....'Z'}
CharSequence = " "
do while(n>0)
{
lsb = n % 26
CharSequence = charLookup[lsb] + CharSequence
floor(n = n/26)
}

- nerd July 09, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 vote

Following is the recursive method to change a number into base 26 and then converting
the resultant number to string.

Recursive because: I wanted to print the last remainder's corresponding char.
This because recall that in binary conversion of decimal number, the last remainder obtained was the most significant.
There can be other versions along with iterative equvalents of it.

void convertToAlpha(long long int num)
{
	long long int q = num;
	long long int r = 0;
	if (num < 1)
		return;
	r = q % 26;
	q = q / 26;
	if (r == 0)
	{
		q = q - 1;
		r = 26;
	}
	if (q == 0)
		printf("%c", (char) (r + 'A' - 1));
	else
	{
		convertToAlpha(q);
		printf("%c", (char) (r + 'A' - 1));
	}
	return;

}

- Pavitra.Ghosh July 10, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This comment has been deleted.

- Administrator July 10, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Your o/p will be printing the string equivalent in reverse order. Eg: for x=28 (or take any other number), it will be printing: "BA", which is reverse order. It should be printing "AB".
Thats why I have used recursion (You can impl iterative version as well)

Even for other programs listed here (except mine) will also be printing the string in reverse order.

- Pavitra.Ghosh July 11, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

hey thanks for pointing that out.... will correct it

- student July 11, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

we need to do %26 but need to take care that 0 has no representation over here....

i.e. when we do % 8 out values are from 0 to 7

but here 0 has no representation ... so every time remainder is 0 we take it as 26 and print 'Z' and subtract 1 from Quotient ....

#include<stdio.h>
#include<math.h>
 
int main()
{
   long long int x = 704;
   char *ptr = (char *)malloc(sizeof(char)); 
 
   // we are skipping any of the decimal points 
   //from input... i.e. error handling is not there
   //right now

   int i=0;
   while(x > 0)
   {
        int r = x%26;
        x = x/26;

        if(r==0)
        {
                *(ptr+i)='Z';
                 i++;
                x = x-1;
        }
        else
        {
                *(ptr+i)=(char)r+'A'-1;
                i++;
        }
 
   }
   *(ptr+i)='\0';
for(i=i-1;i>=0;i--)
   printf("%c",*(ptr+i));
return 0;
}

- student July 11, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/* Disclaimer: This Solution will work upto 2-characters i.e. from A,B,C ------ upto: ZZ */

#include <stdio.h>

#define INVALID_VAL -1

int main()
{
int numb = INVALID_VAL;
char array_alphabets[26] = {'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'};

int Q = INVALID_VAL;
int R = INVALID_VAL;

int row_index = INVALID_VAL;
int col_index = INVALID_VAL;

printf ("\nEnter number: ");
scanf ("%d", &numb);

/* Calculate the position of this number in the Hypothetical 2-D Array
* Hypothetical 2-D Array:
* Row-0: A | B | C | D | .......................... | Z |
* Row-1: AA | AB | AC | AD | .......................... | AZ |
* Row-2: BA | BB | BC | BD | .......................... | BZ |
*
*/

/* Algorithm to determine the Index of Number in Hypothetical 2-D Array:
*
* Step-1: Divide Number by 26, collect the Quotient (Q) & Remainder (R)
Example: Number = 55

55/26 => Q = 2, R = 3

Q => Row No. in Hypothetical Array
R => Column No. in Hypothetical Array

* Step-2: Allocate an Actual 1-D Array of 26 characters

| A | B | C | D | ......................... | Z |

Row-Index of Hypothetical Array = Q-1; [Map to 1-D Array]
Column-Index of Hypothetical Array = R-1; [Map to 1-D Array]
*/


if (numb>26)
{
Q = numb/26;
R = numb%26;

row_index = Q-1;

if (0==R)
{
col_index = 0;
}
else
{
col_index = R-1;
}

printf ("\nAlphabet Equivalent to the Number %d is: %c%c\n", numb,array_alphabets[row_index],array_alphabets[col_index]);
}
else if (numb<=26)
{
printf ("\nAlphabet Equivalent to the Number %d is: %c\n", numb,array_alphabets[numb-1]);
}

return 0;
}

- Sandeep Singh July 12, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This is the same question as posted here: careercup.com/question?id=14097726
See my implementation at the link above.

- ashot madatyan July 12, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include "stdafx.h"
#include <string.h>

void reverseOutput(char *output)
{
int last = strlen(output);
int first=0;
while(first < last )
{
char str = *(output+first);
*(output+first) = *(output+last-1);
*(output+last-1)=str;
last--;first++;
}
}


int _tmain(int argc, _TCHAR* argv[])
{
long int input,store;
printf("Enter the number: ");
scanf("%ld",&input);

store = input;
char output[100];
int j=0;
memset(output,0,100);
while(store != 0)
{
char c = (char)(((store - 1)%26)+97);
output[j++] = c;
store = (store-1)/26;
}
reverseOutput(output);
printf("%s\n",output);
return 0;
}

- polavishnu July 12, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.io.*;
class A
{
   int i=0,j=-1,x,m=1;
    
  void intToAplha(int x)
     {

        int n=0,k=0,counter=0;

     
       while(true)
         {

            n=i*26;

            if(x>n)
              {
                i++;
                j++;
                 
              }
             else
                 break;

          }


      while(true)
       {
           k=702*m ;
            if(x>k)
              {
                 counter++;
                  j=j%26;
                 m++;
              }
            else
              { 
                break;
              }
         }

        System.out.print("The Equivalent String: ");
 
        if(counter>0)
          {
              for(int t=0;t<counter;t++)
                 System.out.print("A");
              if(j==0)
                System.out.print("Z");
           } 
     

        n=x%26;

        if(j>0)
         {
              System.out.print((char)(64+j));
              
              if(n==0)
               System.out.print("Z");
              else
                System.out.print((char)(64+n));
          }
        else
          {
             if(n==0)
               System.out.print("Z");
             else
                 System.out.print((char)(64+n));
          }

       
 
    
  

    
 }

void input()
{
    try{
         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     
         System.out.print("Enter Int Val : ");
          String s=br.readLine();

          x=Integer.parseInt(s);
          
         
          br.close();  
       }
     catch(Exception e){System.out.println(e);}

       
 
       intToAplha(x);
 }
      

      
    

public static void main(String args[])
 {
    A a=new A();
      
      a.input();
      
 }
}

by firoz

- Anonymous July 12, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

void conv(unsigned long int x)
{
unsigned long int y=x%26;
unsigned long int z=x/26;
if(z>1)
{
if(y==0)
ola(z-1);
else
ola(z);
}
else
if(z==1)
if(y!=0)
ola(z);
if(y==0)
y=26;
printf("%c",(y+64));
}

- Deepanjan July 13, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

i tried test cases those obvious ones and result is satisfactory. this is simplest and complete code for the given problem. let me know if it voilate some test cases.

void encrypt(int n)
{
	int r,q=n;
	char *res="";
	while(q>0){
		r=q%26;
		if(r==0){
			q=q-1;
			r=26;
		}
		if(r>0 && r<=26){
			res=appendAtLeft(res,r);
			if(q>0){
				q=q/26;	
			}
		}
	}
	printf("%s\n",res);
}

- zubair alam July 13, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

find the length assign A = 1, B =2,.... Z=26
AAA = 703 = A*(26 square) + A*(26 power 1) + A*(26 power 0) = 1*(26 power 2) + 1*(26) + 1
ZZZ = 26 *( 26 power 2) + 26 *( 26 power 1) + 26 *(26 power 0)

- Arun July 15, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static string ConvertToAlphabet(int number)
        {
            int temp = number;
            char[] alphabets = 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' };
            string Alphabet = string.Empty;
            int Index = 0;

            if (number <= 0)
            {

                Console.WriteLine("input number {0} is invalid", temp);

                return string.Empty;
            }
            
            if (number < 27)
            {

                Console.WriteLine("input number {0} , output alphabet {1}", temp, alphabets[number - 1]);

                return alphabets[number - 1].ToString();
            }
            while (number > 0)
            {
                Index = number % 26;
                number = number / 26; ;

                if (Index == 0)
                {
                    Index = 26;
                    number = number - 1;
                }
                Alphabet = alphabets[Index - 1] + Alphabet;

            }
            
            Console.WriteLine("input number {0} , output alphabet {1}", temp, Alphabet);
            return Alphabet;
        }

input
Microsoft.ConvertToAlphabet(-11);
Microsoft.ConvertToAlphabet(1);
Microsoft.ConvertToAlphabet(26);
Microsoft.ConvertToAlphabet(52);
Microsoft.ConvertToAlphabet(28);
Microsoft.ConvertToAlphabet(702);
Microsoft.ConvertToAlphabet(703);
output

input number -11 is invalid
input number 1 , output alphabet A
input number 26 , output alphabet Z
input number 52 , output alphabet AZ
input number 28 , output alphabet AB
input number 702 , output alphabet ZZ
input number 703 , output alphabet AAA

- ajaypathak July 18, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

public static String convertToInt(int num)
{
String alpha ="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char character = 0;String res ="";
while( num > 0)
{
int id = ( num-1)%26;
res = alpha.charAt(id)+res;
num = (num -1)/26;}

return res;
}

- Deepshikha July 20, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

does this work for input=27

- ruth542 March 02, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

int x,y;
y= n-1;
while(n>0)
{
n = n-1;
if(x = n/26)
printf("%c",((x-1)%26)+65);
else
printf("%c",(y%26)+65);
y = n%26;
n = n/26;
}

- Anonymous August 07, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Try this one:
void convertAphabet(int intx, int base)
{
int inttx = intx;
if(inttx/base > 26)
{
if(inttx%(26*base) == 0)
{

convertAphabet(inttx-26*base, base*26);
putchar('Z');
}else
{
convertAphabet(inttx, base*26);
putchar('A' + (inttx/base)%26 -1);
}
}else
{
putchar('A' + (inttx/base -1));
}
}

- Bin December 13, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ConvertToAlphabet {
	static char[] array;

	static {
		array = new char[27];
		for (int i = 1; i <= 26; i++) {
			array[i] = (char) (i + 96);
		}
	}

	public static String convert(int n) {
		if (n <= 0) {
			return "";
		}
		int remainder = n % 26;
		if (remainder == 0) {
			return "z" + convert((n - 1) / 26);
		} else {
			return array[remainder] + convert(n / 26);
		}
	}

	public static void main(String[] args) {
		System.out.println(convert(702));
	}
}

- Kevin March 09, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

why +96 on line 7, why do you add 96 specifically?

- ruth542 March 14, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

char* ConvertToAlphabet(int x)
{
        char* str = NULL;
	int i = 0;
	int j;

        str = (char* )malloc(N*sizeof(char));
	memset(str, N, 0);

	do {
	    x--;
	    str[i++] = x%26 + 'A';
	} while ( x /= 26 );

	str[i] = '\0';

	printf("str: %s \n", str);

	Reverse(str);

	return str;
}

- Shameek August 19, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

a similar code here

codes-to-problem.blogspot.in/2012/07/wap-to-return-numbered-index-if-input.html

- niraj.nijju July 10, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

the code there gives wrong answer
try BC

- student July 10, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

hey, thanks 

I corrected it. Inform me if u find any other error.

- niraj.nijju July 11, 2012 | Flag
Comment hidden because of low score. Click to expand.


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More