Created
July 26, 2018 07:08
-
-
Save oshea00/987d524dcab24e11641c3c6192d88a52 to your computer and use it in GitHub Desktop.
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
// Implements addition using bit operations (an adder) | |
// This was an answer to a playful Koan test for .Net Core. | |
// I resolved not to use google and work it out from basic | |
// boolean math principles. Could probably be simpler, but was | |
// a fun exercise. | |
public void AdditionWithoutPlusOrMinusOperator() | |
{ | |
var adder = new Func<int,int,int>((a,b)=>{ | |
int c = 0; // carry | |
int s = 0; // sum | |
int t = 0; // total | |
int tmp = 0; | |
int w = 256; // width (2^8 in this case) | |
while ((w >>= 1) > 0) | |
{ | |
s = (a & 1) ^ (b & 1) ^ c; | |
tmp = (a & 1) | ((b & 1) & c); | |
c = tmp & (~tmp | ((b & 1) | c)); | |
a >>= 1; | |
b >>= 1; | |
t = (t >> 1) | (s << 7); | |
} | |
return t; | |
}); | |
//Here goes your implementation to set value to FILL_ME_IN | |
Assert.Equal(255,adder(200,55)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment