Pergunta de entrevista da empresa Google

write a function to calculate X^N

Respostas da entrevista

Sigiloso

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

Sigiloso

20 de jul. de 2010

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

Sigiloso

18 de jan. 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.

Sigiloso

6 de jul. de 2010

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

Sigiloso

6 de jul. de 2010

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