MIPS回文检查

时间:2014-11-04 04:36:02

标签: mips palindrome

我正在尝试编写一个MIPS程序,用于检查输入字符串是否为回文结构。我测试了字符串" HelllleH"当单步执行程序时,我看到在PAL_CHECK的第一个循环期间t0 = 0但t1 = 104.逻辑上,t0 = 0且t1 = 0也在第一个循环中。有人能说出这个程序有什么问题吗?

# a0 is input
# a1 is current character we are looking at 
# a2 is length of string
# t0 is character at beginning of string
# t1 is character at end of string
# v0 stores whether string is palindrome or not (0 for false, 1 for true)

ispalindrome:
    addi    $a2, $0, 0  # length counter

FIND_LEN:
    lbu         $a1, 0($a0) # load character into $a1
    beq         $a1, $0, PAL_CHECK  # Break if string is at the end
    addi    $a2, $a2, 1 # increment counter
    addi    $a0, $a0, 1 # increment str address
    j       FIND_LEN

PAL_CHECK:
    # Is palindrome if length is less than 2
    slti    $t0, $a2, 2
    bne         $t0, $0, RETURN_TRUE

    # Check first and last chars to see if they are the same
    lbu         $t0, 0($a0) # first char is t0
    add         $t1, $a2, $a0 # last char is t1
    lbu         $t1, 0($t1)
    bne         $t0, $t1, RETURN_FALSE # if they are not equal, return false

    # continue recursion
    addi    $a2, $a2, -2
    addi    $a0, $a0, 1
    j       PAL_CHECK

RETURN_FALSE:
    addi    $v0, $0, 0
    jr          $ra

RETURN_TRUE:
    addi    $v0, $0, 1
    jr          $ra

1 个答案:

答案 0 :(得分:3)

在找到字符串的长度时,不断增加$a0以指向下一个字符,直到在字符串末尾找到NUL终止符。你永远不会在回文检查循环之前重置$a0,所以当你开始循环时它仍然指向NUL终止符。因此,您实际上将比较超过字符串的数据。

以这种方式实施支票会更有意义(我用C来说明这个想法;我会把MIPS翻译留给你):

a0 = the_string;
a1 = the_string + strlen(the_string) - 1;
while (a1 > a0) {
    if (*a0 != *a1) return false;
    a0++;
    a1--;
}
return true;

顺便说一句,术语挑剔:# continue recursion。你的实现不是递归的,而是迭代的。