Given two integers a and b, how can we evaluate the sum a + b without using operators such as +, -, ++, –, …?
An interesting way would be:
// May not work with C++ compilers and // may produce warnings in C. // Returns sum of 'a' and 'b' int sum( int a, int b)
{ char *p = a;
return ( int )&p[b];
} |
Despite its awkwardness at first sight, we can easily understand what is happening. First, we created a pointer p. The value of a pointer is a memory address. In this case, the value of p is the address a.
Let’s look the sum’s truth table (forgive the carry for now): Looking carefully, we notice that the sum’s and xor’s truth table are the same. It’s 1 only when the input differs. Now, how can we detect carry? Let’s look the carry’s truth table.
// Returns sum of a and b using bitwise // operators. int sum( int a, int b)
{ int s = a ^ b;
int carry = a & b;
if (carry == 0) return s;
else return sum(s, carry << 1);
} |
This solution has been discussed here.
Let’s remember some facts:
- The printf returns the number of characters printed successfully.
- The specifier %*c requests two parameters: The first one is the customized width and the second is character. For example, printf(“%*c”, 5, ‘a’) will print ” a”.
- The special character ‘\r’ returns the cursor from the beginning of output string. For example, printf(“abcd\r12”) will print “12cd”.
Keeping that in mind, we can understand this function:
// Returns sum of a and b using printf // Constraints: a, b > 0. int sum( int a, int b)
{ return printf ("%*c%*c", a, '\r' , b, '\r' );
} |
This solution has been discussed here.
Method 4 (using conversion)
Unlike above other methods, it doesn’t shows any error or warning in both C and C++.
Here, we add 2 integers using conversion.
// CPP program to check if a given input is a valid integer // or a string #include <bits/stdc++.h> using namespace std;
int sum( int a, int b) { return ( long )&(( char *)( long )a)[b]; }
int main()
{ int st = 12;
int pt = 122;
int ans = sum(st, pt);
printf ( "%d" , ans);
return 0;
} // This code is contributed by Susobhan Akhuli |
// C program to check if a given input is a valid integer or // a string #include <stdio.h> int sum( int a, int b) { return ( long )&(( char *)( long )a)[b]; }
int main()
{ int st = 12;
int pt = 122;
int ans = sum(st, pt);
printf ( "%d" , ans);
return 0;
} // This code is contributed by Susobhan Akhuli |
134
Time Complexity: O(1)
Auxiliary Space: O(1)