Multiplying 2 numbers without using * operator in Java 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 &gt; 0) {
      return x + multiply(x, y - 1);
    } else if (y &lt; 0) {
      return -multiply(x, -y);
    } else {
      return -1;
    }
  }
}


What should I return instead of -1 to make this clear?
The challenge only requires you to work with integers. This technique would not actually be able to multiply two floating-point numbers, so don't use double. A proper solution for integers would not have a failure node that requires you to return -1.

A better algorithm to use would be the Russian peasant method which can be done by bitwise operations and addition.