Implement C=|A-B| with inc,dec,jnz (A,B are non-negative)

前端 未结 3 1103
时光说笑
时光说笑 2021-01-29 15:09

This is a question I saw in an interview :

A,B are non-negative numbers and you need to return C=|A-B| where you have only the following instructions:

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-29 15:41

    The original question as I saw it was:

    Using jnz, inc, dec, and halt implement abs(a - b)

    My answer:

    There is no need to use the mov eax command. just store the result in the result register using the available commands. The solution decrements both A and B until one of them zero, then it sets the value of the other to RES register and halts the program execution. (when the program is halted the result will be in RES register).

    My code would look like this:

    // define/map names to the registers
    #define A   R0
    #define B   R1
    #define RES R2
    
    // This solution uses the assumption that A and B are not holding init value of negative numbers values.
    
    // clear result if not already cleared.
    DEC RES; // in case it was already cleared, this step will prevent counting through all possible values.
    CLEAR_RESULT:
        INC RES;
        JNZ CLEAR_RES;
    
    INC A; // to handle a case of A is initially zero
    INC B; // to handle a case of B is initially zero
    
    DEC_A:
        DEC A;
        JNZ DEC_B;
        //Now A is zero, and the result is B-1;
    SET_B_TO_RES:
        INC RES;
        DEC B;
        JNZ SET_B_TO_RES;
        DEC RES; // compensate the incr that was initially done to handle value of 0 (should only be done here...)
        HALT;
    
    DEC_B:
        DEC B;
        JNZ DEC_A;
        //Now B is zero, and the result is A;
    SET_A_TO_RES:
        INC RES;
        DEC A;
        JNZ SET_A_TO_RES;
        HALT;
    
    // test values:
    // =============
    // A B
    // 0 2 // A is zero
    // 2 0 // B is zero
    // 1 4 // A is smaller than B
    // 5 2 // B is smaller than A
    // 2 2 // A is equal to B
    

提交回复
热议问题