Interview Questions

Implement the function int pow (int a, int b) ....

Microsoft Interview Questions and Answers


(Continued from previous question...)

90. Implement the function int pow (int a, int b) ....

Question:
Implement the function
int pow (int a, int b)
that takes two integers 'a' and 'b' and returns a^b (i.e 'a' raised to the power 'b')
1) Do it using as few multiplication operations as possible.


maybe an answer:


class Math
{
static int Power(int num, int exp)
{
int result = 1;
int count = 0;
while (exp > 0)
{
if ((exp & 0x1) == 0x1)
{
result *= num;
}
exp >>= 1;
num *= num;
count++;
}
Console.WriteLine("\n\tNumber of Iterations : " + count);
return result;
}

public static void Main()
{
Console.Write("\n\tEnter the Number : ");
int number = int.Parse(Console.ReadLine());
Console.Write("\tEnter the Exponent : ");
int exp = int.Parse(Console.ReadLine());
Console.WriteLine("\n\tResult {0} ^ {1} = {2}", number, exp, Power(number, exp));
}
}




maybe an answer2:


double PowerUnsigned(double base, unsigned int exponent) {
if (exponent == 0)
return 0;
if (exponent == 1)
return base;
double result = PowerUnsigned(base, exponent >> 1);
result *= result;
if (exponent & 0x1 == 1)
result *= base;
return result;
}

double Power(double base, int exponent) {
//if (IsZero(base) && exponent > 0)
// return 0;
unsigned int uexponent = static_cast<unsigned int>(exponent);
if(exponent < 0)
uexponent = static_cast<unsigned int>(-exponent);
double result = PowerUnsigned(base, uexponent);
if (exponent < 0)
result = 1.0 / result;
return result;
}double PowerUnsigned(double base, unsigned int exponent) {
if (exponent == 0)
return 0;
if (exponent == 1)
return base;
double result = PowerUnsigned(base, exponent >> 1);
result *= result;
if (exponent & 0x1 == 1)
result *= base;
return result;
}

double Power(double base, int exponent) {
//if (IsZero(base) && exponent < 0)
// return 0;
unsigned int uexponent = static_cast<unsigned int>(exponent);
if(exponent < 0)
uexponent = static_cast<unsigned int>(-exponent);
double result = PowerUnsigned(base, uexponent);
if (exponent < 0)
result = 1.0 / result;
return result;
}

(Continued on next question...)

Other Interview Questions