Skip to content

Instantly share code, notes, and snippets.

@AKIo0O
Created October 30, 2012 11:07
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 AKIo0O/3979635 to your computer and use it in GitHub Desktop.
Save AKIo0O/3979635 to your computer and use it in GitHub Desktop.
add无加号
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);
}
@AKIo0O
Copy link
Author

AKIo0O commented Oct 30, 2012

增加注释

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"],     // 前4个值为0 后4个值为1
        isCarry = [1,2,3,5],                                         // 是否进位
        carry = "0";

    // 前位补0
    a = (Array(max).join("0") + a).slice(-max);
    b = (Array(max).join("0") + b).slice(-max);

    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";                   // 如果大于3,则值为1

        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