Pregunta de entrevista de Google

write a function to calculate X^N

Respuestas de entrevistas

Anónimo

10 de jul de 2010

int pow (int x, int n) { if (n == 0) return 1; if (n == 1) return x; if (n & 0x1) // n odd return pow(x*x, n/2) * x; else // n even return pow(x*x, n/2); } Runtime: O(log n)

9

Anónimo

20 de jul de 2010

i think you need the array way to solve it .. you all are going beyond bounds of an int

Anónimo

18 de ene de 2011

public static long pow(int x, int y) { if(y == 0 || x == 1) return 1; if(y == 1) return x; int pow = 1; long result = x; while((pow<<1) <= y) { result *= result; pow = pow<<1; } return result * (pow == y ? 1 : pow(x,y - pow)); } Almost the same solution like that from mackerzed.

Anónimo

6 de jul de 2010

int pow(int x, int n){ return x*1<

Anónimo

6 de jul de 2010

^^ does not work: int pwr(int x, int n){ int c = x; while(--n) x *= c; return x; }