Last active
December 30, 2015 04:29
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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