Add two numbers without using the addition operator | 5 methods
Given two numbers, add them without using an addition operator.
1. Using subtraction operator
|
1 2 3 |
int add(int a, int b) { return a-(-b); } |
2. Repeated Addition/Subtraction using --/++ operator
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include <iostream> using namespace std; int add(int a, int b) { // to handle positive `a` while (a > 0) { b++; a--; } // to handle negative `a` while (a < 0) { b--; a++; } return b; } int main() { cout << add(5, 8) << " "; cout << add(5, -8) << " "; cout << add(-5, 8) << " "; return 0; } |
Output:
13 -3 3
3. Using printf() function
This method makes use of two facts:
- We can use an asterisk
*to pass the width precision toprintf(), rather than hard-coding it into the format string. printf()function returns the total number of characters printed on the output stream.
Note that we can also use %*c, ' ' replacing %*s, "".
|
1 2 3 4 5 |
int add(int a, int b) { // `%*s` means print a character `*` number of times return printf("%*s%*s", a, "", b, ""); } |
4. Half adder logic
|
1 2 3 4 5 6 7 8 9 10 11 |
int add(int a, int b) { if (!b) { return a; } int sum = a ^ b; int carry = (a & b) << 1; return add(sum, carry); } |
5. Using logarithm and exponential function
|
1 2 3 4 5 6 7 8 9 10 |
#include <stdio.h> int main(void) { int a = 8, b = 6; printf("%g\n", log(exp(a) * exp(b))); return 0; } |
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)