Last active
February 4, 2018 21:50
-
-
Save caglarorhan/aa47ca27d5d89c22aa9ece37a0bef930 to your computer and use it in GitHub Desktop.
Addition and Subtraction Without Operators in Javascript
This file contains hidden or 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 dec2bin(dec){ | |
"use strict"; | |
return dec.toString(2); | |
} | |
function bin2dec(bin){ | |
"use strict"; | |
return parseInt(bin,2); | |
} | |
function full32bit(bitComing){ | |
"use strict"; | |
let fullWith = bitComing<0?"1":"0"; | |
bitComing=bitComing.replace('-',''); | |
let leftFill=[]; | |
for(var cvb=bitComing.length; cvb<32; cvb++){ | |
leftFill.push(fullWith) | |
} | |
leftFill.push(Math.abs(bitComing).toString()); | |
return leftFill.join(''); | |
} | |
function MathOp(a,b) { | |
a = full32bit(dec2bin(a)); | |
b = full32bit(dec2bin(b)); | |
let count=""; | |
let k=0; | |
for(var xv=32; xv>0; xv--){ | |
let r1 = Boolean(parseInt(a[xv])); | |
let r2 = Boolean(parseInt(b[xv])); | |
let c=""; | |
switch(k){ | |
case k=0: | |
if(!r1 && !r2){c="0"; k=0;} | |
else if((r1 && !r2) || (!r1 && r2)){c="1"; k=0;} | |
else if(r1 && r2){c="0"; k=1} | |
break; | |
case k=1: | |
if(!r1 && !r2){c="1"; k=0;} | |
else if((r1 && !r2) || (!r1 && r2)){c="0"; k=1;} | |
else if(r1 && r2){c="1"; k=1} | |
break; | |
} | |
count=c+count; | |
} | |
return bin2dec(count); | |
} | |
console.log(MathOp(-4,5)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try to do Math Operations (adding and subtraction two numbers) wtihout +,-,%,*,/ operators.
Commonly known way is bit operation. I am learning and try to solve.