I saw this interview question and decided to solve using recursion in Java.
Write a multiply function that multiples 2 integers without using *
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter first num: ");
double num = in.nextDouble();
System.out.println("Enter second num: ");
double numTwo = in.nextDouble();
System.out.println(multiply(num, numTwo));
}
private static double multiply(double x, double y) {
if (x == 0 || y == 0) {
return 0;
} else if (y > 0) {
return x + multiply(x, y - 1);
} else if (y < 0) {
return -multiply(x, -y);
} else {
return -1;
}
}
}
What should I return instead of -1 to make this clear?