What is the best way to add two numbers without using the + operator?

后端 未结 22 1663
情书的邮戳
情书的邮戳 2020-11-27 05:18

A friend and I are going back and forth with brain-teasers and I have no idea how to solve this one. My assumption is that it\'s possible with some bitwise operators, but n

22条回答
  •  攒了一身酷
    2020-11-27 05:48

    Note, this would be for an adder known as a ripple-carry adder, which works, but does not perform optimally. Most binary adders built into hardware are a form of fast adder such as a carry-look-ahead adder.

    My ripple-carry adder works for both unsigned and 2's complement integers if you set carry_in to 0, and 1's complement integers if carry_in is set to 1. I also added flags to show underflow or overflow on the addition.

    #define BIT_LEN 32
    #define ADD_OK 0
    #define ADD_UNDERFLOW 1
    #define ADD_OVERFLOW 2
    
    int ripple_add(int a, int b, char carry_in, char* flags) {
        int result = 0;
        int current_bit_position = 0;
        char a_bit = 0, b_bit = 0, result_bit = 0;
    
        while ((a || b) && current_bit_position < BIT_LEN) {
            a_bit = a & 1;
            b_bit = b & 1;
            result_bit = (a_bit ^ b_bit ^ carry_in);
            result |= result_bit << current_bit_position++;
            carry_in = (a_bit & b_bit) | (a_bit & carry_in) | (b_bit & carry_in);
            a >>= 1;
            b >>= 1;
        }
    
        if (current_bit_position < BIT_LEN) {
            *flags = ADD_OK;
        }
        else if (a_bit & b_bit & ~result_bit) {
            *flags = ADD_UNDERFLOW;
        }
        else if (~a_bit & ~b_bit & result_bit) {
            *flags = ADD_OVERFLOW;
        }
        else {
            *flags = ADD_OK;
        }
    
        return result;
    }
    

提交回复
热议问题