Microsoft Interview Question
InternsCountry: India
Interview Type: Written Test
This is correct, only change
if(remainder == 0){
convert(num/26-1)
printf("%c",z);
}
is required instead of printf('a');
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();
}
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"
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"
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
}
}
a better way is to use ASCII codes...like whatever number is given add 65 then print %c in C...
How to differentiate between the two cases:
Input : 27
Expected Output 1 = aa
Expected Output 2 = bg (2->b, 7->g) ???
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);
}
your code doesn't work for 26 and other cases too.
26 - "z"
your code will produce "aa"
#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;
}
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);
}
}
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()
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()
/*
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;
}
#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;
}
#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;
}
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);
}
}
#include<stdio.h>
- kb36 October 26, 2012void 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;
}