Advertisement
fueanta

Sum of two integers without using +/- operators

Sep 6th, 2016
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. /* Problem Description: Sum of two integers without using +/- operators.
  2.  * Author: HTA
  3.  * Date: July 13, 2016
  4.  */
  5.  
  6. #include <iostream>
  7. using namespace std;
  8.  
  9. int add(int,int);
  10.  
  11. int main(void) {
  12.     int a,b;
  13.     cout << "Give a: "; cin >> a;
  14.     cout << endl << "Give b: "; cin >> b;
  15.     cout << endl << "The Sum is: " << add(a,b) << endl;
  16.     return 0;
  17. }
  18.  
  19. int add(int x, int y) {
  20.     if (y==0)
  21.         return x;
  22.     else {
  23.         int sum= x^y;
  24.         int carry= (x&y)<< 1;
  25.         add(sum,carry);
  26.     }
  27. }
  28.  
  29. // alternative:
  30. /*
  31.  *#include <iostream>
  32.  *using namespace std;
  33.  *
  34.  *int main(void) {
  35.  *   int a,b;
  36.  *   cout << "Give a: "; cin >> a;
  37.  *   cout << endl << "Give b: "; cin >> b;
  38.  *   int sum,carry;
  39.  *   while (b!=0) {
  40.  *       sum= a^b;
  41.  *       carry= (a&b);
  42.  *       a=sum;
  43.  *       b=carry <<1;
  44.  *   }
  45.  *   cout << endl << "The Sum is: " << a << endl;
  46.  *   return 0;
  47.  *}
  48.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement