Interview Question

Country: United States

Comment hidden because of low score. Click to expand.
2
of 6 vote

Power(int a, int b){
if (b==0) return 1;
if (a==0) return 0;
if (b%2==0) {
return Power(a*a, b/2);
} else if (b%2==1) {
return a*Power(a*a,b/2);
}
return 0;
}

Comment hidden because of low score. Click to expand.
0

good... But can you give non rec wway of doing the same... ?

Comment hidden because of low score. Click to expand.
0

Power(int a, int b){
if (a==0) return 0;
int res=1;
while(b!=0){
if(b&1==1) res*=a;
a*=a;
b>>=1;}
return res;}

Comment hidden because of low score. Click to expand.
0

good one

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

public static long exp(int a , int n)
{
boolean is_N_Odd = false;
if ( n % 2 > 0 )
{
n++;
is_N_Odd =true;
}

if ( n == 2 )
return a * a;
else if (n == 1 )
return a;
else
{
long calc = exp (a , n/2) ;
if ( is_N_Odd )
return calc * calc /a;
else
return calc * calc ;
}
}

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

int CalculatePower(int base, int power)
{
int result = 1;
if(power == 0){
result = 1;
return result;
}

for(int i = 1; i<= power; i++){
result = result * base;
}

return result;
}

Comment hidden because of low score. Click to expand.
0
of 2 vote

Pow(n,exp)
{
if(exp==0)
return 1;
else
Pow(n,exp-1);
}

Comment hidden because of low score. Click to expand.
0

This is not the best you can do. Check my post. It runs in O(log n).

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

The interviewer is looking for a Divide&Conquer Solution

x = a.a.a.a.a.a.....(n times)

x = (a^n/2)*(a^n/2) if n is even
= (a^(n-1/2)) * (a^(n-1/2)) * a if n is off

So basically the algorithm goes like :

Problem : Calculate Power of n : Complexity T(n)
1. Divide the question in 2 halves : Complexity O(1)
2. Conquer : Multiple the halves : Complexity T(n/2)
3. Combine : Trivial : Complexity T(1)

T(n) = T(n/2) + Constant
Using Master Method, Complexity is O(log n)

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.

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.