Last active
October 3, 2016 16:12
-
-
Save willeccles/f35107442113a009507c50802082c76e to your computer and use it in GitHub Desktop.
Add and subtract ints in C++ without using + or - operators.
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
#include <iostream> | |
// not sure why i included this but now i will just leave it here. yolo | |
#include <string> | |
// add a and b | |
int binadd(int a, int b) { | |
int carry = (a & b) << 1; | |
int result = a ^ b; | |
if (carry == 0) | |
return result; | |
else | |
result = binadd(result, carry); | |
return result; | |
} | |
// subtract b from a | |
int binsub(int a, int b) { | |
// binadd(~b, 1) = two's complement of b, AKA -b | |
return binadd(a, binadd(~b, 1)); | |
} | |
int main(int argc, char* argv[]) { | |
std::cout << binadd(5, 1) << std::endl; | |
std::cout << binadd(12, 12) << std::endl; | |
std::cout << binsub(5, 1) << std::endl; | |
std::cout << binsub(12, 12) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment