Question d’entretien chez Google

write a function to calculate X^N

Réponses aux questions d'entretien

Utilisateur anonyme

10 juil. 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

Utilisateur anonyme

20 juil. 2010

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

Utilisateur anonyme

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

Utilisateur anonyme

6 juil. 2010

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

Utilisateur anonyme

6 juil. 2010

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