实现C = | A-B |用INC,DEC,JNZ(A,B都是非负) [英] Implement C=|A-B| with inc,dec,jnz (A,B are non-negative)

查看:259
本文介绍了实现C = | A-B |用INC,DEC,JNZ(A,B都是非负)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is a question I saw in an interview :

A,B都是非负数和你需要返回C = | A-B |在这里你只有以下说明:

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


      
  • INC寄存器 - 增加了一个注册

  •   
  • DEC寄存器 - 减去一个来自寄存器

  •   
  • JNZ LABEL - 跳转到标签如果最后的指令结果不是零

  •   

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

In addition you can use other registers that their initial value is zero.

我将如何去解决呢?

推荐答案

就都在一个循环递减,直到其中一个得到为零。另一个明显的结果。

Just decrement both in a loop until one of them gets to be zero. The other is obviously the result.

    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

这篇关于实现C = | A-B |用INC,DEC,JNZ(A,B都是非负)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆