Created
October 30, 2012 11:07
-
-
Save AKIo0O/3979635 to your computer and use it in GitHub Desktop.
add无加号
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
function add(a,b){ | |
var a = a.toString(2), | |
b = b.toString(2), | |
max = a.length > b.length ? a.length : b.length, | |
result = "", | |
res = ["000","110","101","011","001","111","100","010"], | |
isCarry = [1,2,3,5], | |
carry = "0"; | |
a = (Array(max).join("0") + a).slice(-max); | |
b = (Array(max).join("0") + b).slice(-max); | |
console.log(a,b); | |
var _add = function(a,b) { | |
var i, j, name, index, value; | |
i = a.slice(-1); | |
j = b.slice(-1); | |
name = i + j + carry; | |
index = res.indexOf(name); // 结果的index | |
carry = isCarry.indexOf(index) > -1 ? "1" : "0"; | |
value = index > 3 ? "1" : "0"; | |
result = value + result; | |
if(a.length === 1) return result; | |
a = a.slice(0,-1); | |
b = b.slice(0,-1); | |
return _add(a,b); | |
}; | |
return parseInt(_add(a,b),2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
增加注释