Subtracting two numbers without using '-' operator

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

    You also can implement this recursively. In C this might look like:

    #include 
    
    int add(int a, int b){
        if(b == 0) return a;
        int sum = a ^ b;
        int carry = (a & b) << 1;
        return add(sum, carry);
    }
    
    int subtract(int a, int b){
        return add(a, add(~b, 1));
    }
    
    int main(){
    
        int a = 3;
        int b = 1;
    
        int sum = add(a, b);
        printf("%i + %i = %i \n", a, b, sum);
    
        int difference = subtract(a, b);
        printf("%i - %i = %i \n", a, b, difference);
    
        return 0;
    }
    

提交回复
热议问题