Microsoft Interview Question
Software Engineer / DevelopersTeam: Bing
Country: India
Interview Type: In-Person
If you count like this, then AAA == 0
So I think you should use add +1 to (A-A) and e t.c.
Also you should add +1 to 26^2 because column index starts from 1 == A till 26 == Z so AA == 26^1 +1.
So the result will be smth like this:
BAD;
(26^2 + 1) * (B - A + 1) + (26^1 + 1) * (A - A + 1) + (26^0 + 1) * (D - A + 1)
Correct me if I am wrong
char[] charArray = "BAD".ToLower().ToCharArray();
int constant = 26;
int number = 0;
for (int i = 0; i < charArray.Length ; i++)
{
int multiplier = (charArray[i] - 'a') + 1;
number = number + (multiplier * constant);
}
//int i = Convert.ToInt16('b') - Convert.ToInt16('a');
Console.WriteLine(number.ToString());
Console.Read();
#include<stdio.h>
#include<string.h>
#include<math.h>
int isoperand (char e);
int main()
{
char e[10];
int i, j, x, n, powr;
double sum = 0;
printf("\nEnter the string\n");
gets(e);
n = strlen(e);
printf("\n%d\n", n);
for(i = n-1, j = 0; j <= n-1; i--, j++)
{
if(1 == isoperand(e[i]))
{
x = e[j] - 'A' + 1;
sum = sum + (pow(26, i) * x);
}
else
{
printf("Wrong input");
exit();
}
}
printf("The string is %s and its equivalent number is %f", e, sum);
}
int isoperand(char e)
{
if(e >= 'A' && e <= 'Z')
return 1;
else
return 0;
}
This is exactly like converting a string to int.
While converting a string to integer, initially we keep the result as zero. Then multiply result by 10 and add the current digit (corresponding to the current character) to the result; We keep doing it until all the characters in the input string are visited.
The only change to this problem is,
1. We have to map the character from A-Z to 1-26
2. Start with result=0 and multiply result with 26 and then add the digit value corresponding to the current character.
Suppose if the input is 'BAD', then,
1. result = 0
2. result = (result*26) + 'B'-'A'+1 (adding 1 at the end so as to map 'A' to 1)
3. result = (result*26) + 'A'-'A'+1
4. result = (result*26) + 'D'-'A'+1
return result.
Wrong answer!!! for BAD the calculation is 2732 and the correct answer is 707.
I try with AB and the result is 53 and really is 28.
the correct answer to calculate the number is using the @abhishekatuw formula
the correct answer for the BAD should be 1382!! .its not 707.
the correct formula which i believe
BAD:
(B-A+1)*(26^2)+(A-A+1)*(26^1)+(D-A+1)*(26^0)
where A=1 B=2..... Z=26
For BAD should be 1382.
@geeeks ' s algoirthm is correct.
(B-A+1)*(26^2)+(A-A+1)*(26^1)+(D-A+1)*(26^0)
1. This is simple base 26 system with little modifications
2. values for A...Z are 1..26
3. Now for next AA this will be (getValue(A)*26^1 + getValue(A)*26^0)
3. Now for next CA this will be (getValue(C)*26^1 + getValue(A)*26^0)
You can use this formula to get any string value like ABCDD
BAD;
- abhishekatuw January 22, 201226^2 * (B-A) + 26^1 * (A-A) + 26^0 * (D - A)