From 22ee3ce03f74349ed3b0f36bfdf1dc119e2be70b Mon Sep 17 00:00:00 2001 From: Isaac Cisneros Date: Sat, 16 May 2015 01:15:38 +0200 Subject: [PATCH] Remove the '*' operator completely from the algorithm --- .../problem20/MultiplicationWithoutMultiply.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/pedrovgs/problem20/MultiplicationWithoutMultiply.java b/src/main/java/com/github/pedrovgs/problem20/MultiplicationWithoutMultiply.java index 63d6ec12..cbab0f11 100644 --- a/src/main/java/com/github/pedrovgs/problem20/MultiplicationWithoutMultiply.java +++ b/src/main/java/com/github/pedrovgs/problem20/MultiplicationWithoutMultiply.java @@ -32,15 +32,16 @@ public class MultiplicationWithoutMultiply { */ public int calculate(int n1, int n2) { int result = 0; - boolean negative = n1 < 0; + boolean negative = (n1 < 0 && n2 >= 0) || (n2 < 0 && n1 >= 0); + boolean positive = !negative; n1 = Math.abs(n1); for (int i = 0; i < n1; i++) { - result += n2; + if (negative && n2 > 0 || positive && n2 < 0) + result -= n2; + else + result += n2; } - if (negative) { - result *= -1; - } return result; } }