天天看點

純粹依靠位操作實作整數加法運算

<html>
<script>
function add(a,b){
    var n = 0;
    // var c = false;
    var c = 0;
    for( var i = 1; i != 0; i = i << 1) {
        var _a = (a & 1 ) == 1;
        var _b = (b & 1 ) == 1;
        var _n = (_a ^ _b ) ^ c;
        c = _a &  (_b | c ) | ( _b & c );
        n = n | (_n ? i : 0);
        a = a >> 1;
        b = b >> 1;
    }
    return n;
}

alert( add(21,32));
</script>
</html>      

繼續閱讀