Subtracting two numbers without using '-' operator

前端 未结 5 2062
北荒
北荒 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:48

    Considering how negative numbers are represented, the following will compute a - b:

    int a, b, c;
    // assign to a and b
    c = a + (~b + 1); // () not needed, just to show the point
    

    as the OP already noted:) This moves the attention to your add implementation, that is of course wrong. The following is an odd way to do it (just since other better ways are already given)

    int add1(int a, int b, int *c)
    {
      int r = *c & 1;
      a &= 1; b &= 1;
      *c = a&b | a&r | b&r;
      return a^b^r;
    }
    int inv(int a)
    {
      int i, r = 0;
      for(i = 0; i < sizeof(int)*8; i++)
      {
        r = r<<1 | (a&1);
        a >>= 1;
      }
      return r<<1;
    }
    int add(int a, int b)
    {
      int r = 0, i;
      int c = 0;
      for(i=0; i < sizeof(int)*8; i++)
      {
        r |= add1(a>>i, b>>i, &c);
        r <<= 1;
      }
      return inv(r);
    }
    
    int sub(int a, int b)
    {
      return add(a, add(~b, 1));
    }
    

    (keeping the same idea the code can be made better, just too tired to do it finer)

提交回复
热议问题