Subtracting two numbers without using '-' operator

前端 未结 5 2051
北荒
北荒 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 18:07

    add method implementation is incorrect. do like this -> A java way of this.

    public int add(int a, int b){
      do {
        a = a & b; //carry
        b = a ^ b;  //addition
        a = a << 1; //carry shift to one bit left
      }while(a != 0);  //exit 
      return b;     //addition result
    }
    
      public int sub(int a, int b){
        return add(a, add(~b, 1)); 
    
      }
    

提交回复
热议问题