实施C = | A-B |与inc,dec,jnz(A,B是非负的)

时间:2016-02-15 16:21:43

标签: assembly

这是我在采访中看到的一个问题:

  

A,B是非负数,您需要返回C = | A-B |您只有以下说明:

     
      
  • INC注册 - 添加一个注册
  •   
  • DEC寄存器 - 从寄存器中减去一个
  •   
  • JNZ LABEL - 如果最后一条指令结果不为零,则跳转到标签
  •   
     

此外,您可以使用其初始值为零的其他寄存器。

我将如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

只需在循环中递减,直到其中一个变为零。另一个显然是结果。

    inc a
    inc b      ; make sure input is not zero
loop:
    dec a
    jnz skip
    dec b
    mov eax, b ; return b as answer
    ret
skip:
    dec b
    jnz loop
    mov eax, a ; return a as answer
    ret

答案 1 :(得分:2)

仅允许指示的解决方案可能(虽然不优雅)。 伪寄存器 a b 保存操作数,伪寄存器 c 结果(如上所述,最初为零)。

_dec_a:
 dec a
 inc a
jnz _dec_b

;a is zero here

  _a_zero_dec_b:
   dec b
   inc b
  jnz _a_zero_b_non_zero

;a and b are zero here 

   ;;C is the result
   inc c
   jnz _result

 _a_zero_b_non_zero:
   dec b
   inc c
 jnz _a_zero_dec_b

   ;CANNOT FALL HERE

_dec_b:
 dec b
 inc b
jnz _subtract

;b is zero here

 _b_zero_dec_a:
  dec a
  inc a
 jnz _b_zero_a_non_zero

;a and b are zero here

  ;; C is the result
  inc c
  jnz _result

 _b_zero_a_non_zero:
  dec a
  inc c
 jnz _b_zero_dec_a

  ;CANNOT FALL HERE


_subtract:
 dec a
 dec b
jnz _dec_a

 ;Result
_result:
 dec c

答案 2 :(得分:0)

我看到的原始问题是:

使用jnz,inc,dec和halt实现abs(a - b)

我的回答:

无需使用mov eax命令。只需使用可用命令将结果存储在结果寄存器中。 解决方案递减A和B,直到其中一个为零,然后将另一个的值设置为RES寄存器并停止程序执行。 (当程序暂停时,结果将在RES寄存器中)。

我的代码看起来像这样:

// 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