Skip to content

Instantly share code, notes, and snippets.

@jasonsperske
Last active December 30, 2015 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonsperske/7776047 to your computer and use it in GitHub Desktop.
Save jasonsperske/7776047 to your computer and use it in GitHub Desktop.
A Google Interview question I was asked over a year ago (and didn't know the answer to). I've since learned how and here is a quick solution in JavaScript (qunit demo at http://jsfiddle.net/at4gU/). I wanted to make something Lisp-y so it takes multiple arguments, deals with negative numbers and passes JSLint (well except for the bitwise operato…
/*jslint bitwise: true */
var multiply = function () {
'use strict';
var fn = function (a, b, product) {
if (a > 0) {
return fn(a >> 1, b << 1, product + (a % 2 === 1 ? b : 0));
}
return product;
},
factors = Array.prototype.slice.call(arguments),
product = factors.pop();
while (factors.length > 0) {
if (product < 0) {
product = ~fn(~product + 1, factors.pop(), 0) + 1;
} else {
product = fn(product, factors.pop(), 0);
}
}
return product;
};
//Use it like this:
alert(multiply(-3,5,-4)); //Returns 60 (-3 x 5 x -4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment