Microsoft Interview Question for Interns


Country: India
Interview Type: Written Test




Comment hidden because of low score. Click to expand.
4
of 4 vote

#include<stdio.h>
void convert( unsigned int );
int main()
{
unsigned int num = 0;
printf("Enter number: \n");
scanf("%u", &num);
convert(num);
printf("\n");
return 0;
}

void convert(unsigned int num)
{
int remainder;
if (num <= 26)
printf("%c", num -1 + 'a');
else {
remainder = num % 26;
if(remainder == 0) {
convert(num/26-1);
printf("%c", 'a');
}
else {
convert(num/26);
printf ("%c", remainder -1 + 'a');
}
}
return;
}

- kb36 October 26, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is correct, only change

if(remainder == 0){
     convert(num/26-1)
      printf("%c",z);
 }

is required instead of printf('a');

- artemis October 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

void convert (unsigned int n)
{
if(n<=0)
return;
int rem = (n-1)%26;
convert((n-1)/26);
printf("%c", rem + 'a');
}

- Gurman November 03, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

public static final byte OFFSET = 97;
	public static final byte ALPHA_SIZE = 26;
	
	public static String encodeString(int n)
	{
		StringBuilder builder = new StringBuilder();
		
		while (n > 0)
		{
			char encodedChar = (char) (((n - 1) % ALPHA_SIZE) + OFFSET);
			builder.append(encodedChar);
			n = (n - 1) / ALPHA_SIZE;
		}
		
		return builder.reverse().toString();
	}

- Sean A November 05, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

A solution in Python 2.

#!/usr/bin/python2

""" Given a positive integer, decode it into a string in following way :-
1 - a, 2 - b,3 - c,...26 - z, 27 - aa, 28 - ab........and so on."""

import string

mapping = dict(zip(range(1, 27), string.ascii_lowercase))


def base26(n):
    output = ""
    base = 26
    while n >= base:
        output = mapping[n % base] + output
        n = n / base
    output = mapping[n % base] + output
    return output


if __name__ == "__main__":
    assert base26(27) == "aa"
    assert base26(28) == "ab"

- webie October 24, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Fixed solution.

import string

mapping = dict(zip(range(1, 27), string.ascii_lowercase))


def base26(n):
    output = ""
    base = 26
    while n > base:
        output = mapping[n % base] + output
        n = n / base
    output = mapping[n] + output
    return output


if __name__ == "__main__":
    assert base26(26) == "z"
    assert base26(27) == "aa"
    assert base26(28) == "ab"

- webie October 24, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

it will not work for n=52..
n>base
so output = mapping[0] + output; // mapping[0] is "a"
output = "a"

now output = mapping[2] + output
output = ca whereas answer should be "az"

- Anonymous October 26, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 vote

Hers is the java code:

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {

        System.out.println("Enter number = ");
        Scanner scan = new Scanner(System.in);
        Integer number = scan.nextInt();
        Integer base = 26;

        Integer remainder = null;
        String result = "";
        while (number > 26) {
            remainder = number % base;
            result = mapping(remainder) + result;
            number = (number / base);

        }
        result = mapping(number) + result;

        System.out.println("result=" + result);
    }

    private static String mapping(Integer mapping) {
        // gives the mapping for corresponding integer
        // 1->a, 2 ->b,  0,26->z
    }
}

- Mario October 24, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

a better way is to use ASCII codes...like whatever number is given add 65 then print %c in C...

- sharda October 24, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This solution doesn't work it sends 0 and 2 to mapping if I entered 52 which means BZ according to your solution but this is not correct answer. I have expected AZ as result.

- HB October 24, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

How to differentiate between the two cases:
Input : 27
Expected Output 1 = aa
Expected Output 2 = bg (2->b, 7->g) ???

- Learner October 24, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

"bg" = 59
a - z --- 1 - 26
aa - az --- 27 - 52

- @ce October 24, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Java based recursive solution:

public static String  str="aabcdedfghijklmnopqrstuvwxyz";
	public static String mapping(int n){
		
		if(n==0) return "";		
		return mapping(n/26)+str.charAt(n%26);				
	}

- pradegup October 24, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

your code doesn't work for 26 and other cases too.
26 - "z"
your code will produce "aa"

- @ce October 24, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@ce: Yes you are right.
I did modification in code to now it should work.

public static String mapping(int n){
		
		if(n<=26) return ""+str.charAt(n);
		if(n%26==0){
			return mapping((n/26)-1)+"z";
		}else{
			return mapping(n/26)+str.charAt(n%26);
		}
	}

- pradegup November 05, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <map>
#include <string>

#define base 26

using namespace std;
typedef map<int, char> dictionary;

string notEdgeCase(int num, dictionary dict){

bool needReverse = false;
string output;
while( num > base && num % base != 0){
output.append(1, dict[num % base]);
num = num/base;
needReverse = true;
}

if(num % base !=0 && num < base){
output.append(1, dict[num]);
}

// Reverse the string and then return
if(needReverse){
int length = output.length() - 1;
int temp = 0;
char ch;

for(; temp<length; temp++){
ch = output[temp];
output[temp++] = output[length];
output[length--] = ch;
}
}

return output;
}


int main(){
int inputNumber = 707;
dictionary localDict;
int count = 1;
int temp = 1;;
string result;

// Initialize the dictionary
for(int i=97; i<=122; i++){
localDict[count++] = i;
}

if(inputNumber == 0){
result.append("Invalid Number passed\n");
}
else if(inputNumber <= base){
result.append(1, localDict[inputNumber]);
}
else if(inputNumber%base == 0 && inputNumber>0){
temp = inputNumber/base;
result = notEdgeCase(temp -1, localDict);
result.append(1, 'z');
}
else{
result = notEdgeCase(inputNumber, localDict);
}

cout << "Output: " << result << endl;

return 0;
}

- Anonym October 26, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void decode(int n){ 
        char ch; 
        if( n < 26) {
                ch = 'A' + n;
                cout<<ch;
        }   
        else{
                ColumnNumToChar(n/26 - 1); 
                ColumnNumToChar(n%26);
        }   
}

if given n then call the function as decode(n-1)

- Nagarjuna October 26, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.io.*;

class microsoftQ
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number ");
int i=Integer.parseInt(br.readLine());
int d=i/26;

int mod=i%26;
int l=d-1;
String s=" ";
int c=0;
while(c<=l)
{
s+="a";
c++;
}

switch(mod)
{
case 1:s+="a";
break;
case 2:s+="b";
break;
case 3:s+="c";
break;
case 4:s+="d";
break;
case 5:s+="e";
break;
case 6:s+="f";
break;
case 7:s+="g";
break;
case 8:s+="h";
break;
case 9:s+="i";
break;
case 10:s+="j";
break;
case 11:s+="k";
break;
case 12:s+="l";
break;
case 13:s+="m";
break;
case 14:s+="n";
break;
case 15:s+="o";
break;
case 16:s+="p";
break;
case 17:s+="q";
break;
case 18:s+="r";
break;
case 19:s+="s";
break;
case 20:s+="t";
break;
case 21:s+="u";
break;
case 22:s+="v";
break;
case 23:s+="w";
break;
case 24:s+="x";
break;
case 25:s+="y";
break;
case 26:s+="z";
break;
}


System.out.println("the string to be printed is "+s);
}
}

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

Nearly all of these solutions are overcomplicated. This should only require a division and a modulo operation.

import math

def computeString(n):
    if not n:
        return 'Invalid Input';

    result = ''
    occurrences = int(n/27)
    if occurrences:
        result += 'a' * occurrences

    last = n % 27
    if last:
        result += chr(96 + last)
    return result

def main():
    assert computeString(26) == 'z'
    assert computeString(0) == 'Invalid Input'
    assert computeString(1) == 'a'
    assert computeString(53) == 'az'
    assert computeString(54) == 'aa'

if __name__ == '__main__':
    main()

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

import math

def computeString(n):
    if not n:
        return 'Invalid Input';

    result = ''
    occurrences = int(n/27)
    if occurrences:
        result += 'a' * occurrences

    last = n % 27
    if last:
        result += chr(96 + last)
    return result

def main():
    assert computeString(26) == 'z'
    assert computeString(0) == 'Invalid Input'
    assert computeString(1) == 'a'
    assert computeString(53) == 'az'
    assert computeString(54) == 'aa'

if __name__ == '__main__':
    main()

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

Answer = convert(rank - 1)

convert(x){
if(x > 26)convert(x/26);
cout << (x%26)+'a';
}

- coder November 01, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*
Given a positive integer, decode it into a string in following way :-
1 - a, 2 - b,3 - c,...26 - z, 27 - aa, 28 - ab........and so on.
*/
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
char array[26];
for(int i=0;i<26;i++)
array[i]=97+i;
string x;
while(n!=0)
{
char c=array[n%26-1];
x=c+x;
n/=26;
}
cout<<x<<endl;
system("pause");
return 0;
}

- Kapil Agarwal November 07, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>   // Author : Jeevan B.Manoj, TKMCE
#include<stdlib.h>
using namespace std;
int main()
{
    int x,flag=0;
    char c=96,str[100];
    cout<<"\nEnter value of x  ";
    cin>>x;
    int p=0;
    str[0]=c;
    str[1]='\0';
    while(1)
    {
        for(int i=1;i<=26;i++)
        {
            flag=0;
            c=str[p];
            c++;
            str[p]=c;
            str[p+1]='\0';
            x--;
            if(x==0)
            {
                flag=1;
                break;
            }
        }
        if(flag)
            break;
        str[p]=97;
        p++;
        str[p]=96;
        str[p+1]='\0';
    }
    cout<<"\n"<<str;
    return 0;
}

- Jeevan B Manoj November 09, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>

using namespace std;

void convert(int a)
{
if(a!=0)
{
                 int n=a%26;
                 if(n!=0)
                 {
                 convert(a/26);
                 cout<<(char)(96+n);
                 }
                 else
                 {convert((a/26)-1);
                 cout<<"z";
                 }
             
}               
}
int main()

{
    
    int a;
    cout<<"Enter number";
    cin>>a;
    convert(a);
    system("pause");
    return 0;
}

- sahil.bathla1 November 12, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
using namespace std;

int convert(int num)
{
        int t1=0,t2=0;
       
         
        if (num <= 26)
        {
            cout<< char('a'+num-1);
        }
        else
        {
            t1=num%26;
            t2=(num/26);
            
            if (t2 > 26)
            {
                t2=convert(num/26);
            }
            
            cout<<char('a'+t2-1);
            cout<<char('a'+t1-1);
            
        }
}

int main() {

	int num = 0;
	cin >> num;
    convert(num);
	return 0;

}

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

void convert(int num)
{
    if(num==0)
        return;
     int j = num % 26;
    convert(num/26);
    printf("%c",j+96);    
}

- WeAreBack November 19, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
#include<conio.h>

using namespace std;
void convert(int n)
{
 if(n<=0)
     return;
 if(n<=26)
   printf("%c",'a'+ n-1);
 else{
      convert(n/26);
      convert(n%26);
      }
}
int main()
{
   int a;
   while(1)
   {
   cout<<"INPUT=>";
   cin>>a;
   if(a==0)
      break;
   convert(a);
   cout<<endl;
    }
}

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

public class DecodeInteger {

	public static char[] array;

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

	public static void decodeInt(int num) {
		int remainder;
		if (num <= 26) {
			System.out.print(array[num]);
		} else {
			remainder = num % 26;
			if (remainder == 0) {
				decodeInt(num / 26 - 1);
				System.out.print("z");
			} else {
				decodeInt(num / 26);
				System.out.print(array[remainder]);
			}
		}
	}

	public static void main(String[] args) {
		decodeInt(26);
	}

}

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

void convert(int curSum)
{
  if (curSum == 0) return;
  convert(curSum / 26);
  int x = curSum % 26;
  printf("%c ", 96 + x);
}
int main()
{
  int input = 0;
  printf("Get Number ");
  scanf("%d", &input);
  convert(input);
  return 0;
}

- Anonymous September 08, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

what will be the out put??

#include<stdio.h>
#define SQR(x) (x*x)
int main(){
int a,b=3;
a= SQR(b+2);
printf("%d",a);
return 0;
}

- Anonymous October 24, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

11

- pradegup October 24, 2012 | Flag


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