Microsoft interview question

multiply 2 numbers without using * sign

Interview Answers

Anonymous

25 May 2015

int MyMul(int a, int b) { int result = 0; while (b > 0) { if ((b & 1) == 1) { result += a; } b >>= 1; a <<= 1; } return result; }

2

Anonymous

15 Jun 2015

We need to handle cases where both inputs are positive, both are negative, or one is positive and the other is negative: public static int mult(int a, int b) { int product = 0; boolean positiveProduct = !(a >= 0 ^ b >= 0); a = Math.abs(a); b = Math.abs(b); int min = Math.min(a, b); int max = Math.max(a, b); while (min > 0) { if (positiveProduct) product += max; else product -= max; min--; } return product; }

1

Anonymous

29 Jun 2015

import java.util.Scanner; public class MultiplyWithoutSign{ public static void main(String args[]){ Scanner in = new Scanner(System.in); System.out.println("Enter the two numbers"); int x = in.nextInt(); int y = in.nextInt(); int sum=0; for( int i =0; i