HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Multiplying 2 numbers without using * operator in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withoutoperatormultiplyingnumbersjavausing

Problem

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?

Solution

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.

Context

StackExchange Code Review Q#157344, answer score: 4

Revisions (0)

No revisions yet.