public class Solution {
public double pow(double x, int n) {
if(n == 0)
return 1;
if(n<0){
n = -n;
x = 1/x;
}
return (n%2 == 0) ? pow(x*x, n/2) : x*pow(x*x, n/2);
} }
Apart from coding and design interview questions, this page contains updates on my learnings with Java. It helps me organize my learning. Read about my future self here : https://siliconvalleystories.blogspot.com/
public class Solution {
public double pow(double x, int n) {
if(n == 0)
return 1;
if(n<0){
n = -n;
x = 1/x;
}
return (n%2 == 0) ? pow(x*x, n/2) : x*pow(x*x, n/2);
} }
class Solution {
private int[] prefixSums;
private int totalSum;
public Solution(int[] w) {
this.prefixSums = new int[w.length];
int prefixSum = 0;
for (int i = 0; i < w.length; ++i) {
prefixSum += w[i];
this.prefixSums[i] = prefixSum;
}
this.totalSum = prefixSum;
}
public int pickIndex() {
double target = this.totalSum * Math.random();
int i = 0;
// run a linear search to find the target zone
for (; i < this.prefixSums.length; ++i) {
if (target < this.prefixSums[i])
return i;
}
// to have a return statement, though this should never happen.
return i - 1;
}
}