Subtraction without minus sign in C

后端 未结 17 1999
栀梦
栀梦 2020-12-31 10:26

How can I subtract two integers in C without the - operator?

17条回答
  •  执笔经年
    2020-12-31 10:59

    Given that encoding integers to support two's complement is not mandated in C, iterate until done. If they want you to jump through flaming hoops, no need to be efficient about it!

    int subtract(int a, int b)
    {
      if ( b < 0 )
        return a+abs(b);
      while (b-- > 0)
        --a;
      return a;
    }
    

    Silly question... probably silly interview!

提交回复
热议问题