Domanda di colloquio di Google

write a function to calculate X^N

Risposte di colloquio

Anonimo

10 lug 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

Anonimo

20 lug 2010

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

Anonimo

18 gen 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.

Anonimo

6 lug 2010

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

Anonimo

6 lug 2010

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