Subtracting two numbers without using '-' operator

前端 未结 5 2149
北荒
北荒 2021-02-04 17:07

i tried with the following code , but i can\'t understand why it\'s giving me wrong answer. i am computing the 2\'s complement and adding with another no.

#inclu         


        
5条回答
  •  感动是毒
    2021-02-04 17:59

    i used a different add() function as suggested by NullUserException, it works now:

    int add(int a,int b)
    {
      int x;
      x = a^b;
    
      while(a&b)
      {
        b = ((a&b)<<1);
        a = x;
        x = a^b;
        //b=(a^b);
      }
    
      return x;
    }
    

提交回复
热议问题