Created
January 27, 2018 20:54
-
-
Save jianminchen/aff4ccbf1e70f1c5b07e5124f9247ba1 to your computer and use it in GitHub Desktop.
Root of number - mock interview 12:00 PM -
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
class Solution { | |
static double root(double x, int n) { | |
if (x == 0 || x == 1){ | |
return x; | |
} | |
if (n == 1){ | |
return x; | |
} | |
double lo = 0; | |
double hi = Math.max(1, x); | |
int iterations = 200; | |
double guess = 0; | |
while(iterations > 0){ | |
iterations--; | |
guess = lo + (hi-lo)/2; | |
double guessResult = exp(guess,n); | |
if (guessResult <= 0 || guessResult > x){ | |
hi = guess; | |
} else { | |
lo = guess; | |
} | |
} | |
return guess; | |
} | |
private static double exp(double x, int n){ | |
if (n == 1) { | |
return x; | |
} | |
double result = 1; | |
double base = x; | |
while(n > 0){ | |
if ((n&1) != 0){ | |
result *= base; | |
} | |
base *= base; | |
n >>= 1; | |
} | |
return result; | |
} | |
public static void main(String[] args) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment