multiply two numbers without using arithmetic operators in java

Solutions on MaxInterview for multiply two numbers without using arithmetic operators in java by the best coders in the world

we are a community of more than 2 million smartest coders
registration for
employee referral programs
are now open
get referred to google, amazon, flipkart and more
register now
  
pinned-register now
showing results for - "multiply two numbers without using arithmetic operators in java"
Angela
09 Feb 2016
1import java.util.Scanner;
2public class MultiplyWithoutArithmeticOperators
3{
4   static int multiplyNumber(int num1, int num2)
5   {
6      int output = 0;
7      boolean boolNegative = (num1 < 0 && num2 >= 0) || (num2 < 0 && num1 >= 0);
8      boolean boolPositive = !boolNegative;
9      num1 = Math.abs(num1);
10      for(int a = 0; a < num1; a++)
11      {
12         if(boolNegative && num2 > 0 || boolPositive && num2 < 0)
13         {
14            output -= num2;
15         }
16         else
17         {
18            output += num2;
19         }
20      }
21      return output;
22   }
23   public static void main(String[] args)
24   {
25      Scanner sc = new Scanner(System.in);
26      System.out.print("Please enter first number: ");
27      int num1 = sc.nextInt();
28      System.out.print("Please enter second number: ");
29      int num2 = sc.nextInt();
30      System.out.println("Multiplication of two numbers: " + multiplyNumber(num1, num2));
31      sc.close();
32   }
33}