2014-11-04 41 views
1

我想写一个MIPS程序,检查输入字符串是否是回文。我测试了字符串“HelllleH”,并且在单步执行程序时,我发现在PAL_CHECK t0 = 0的第一个循环中,但是t1 = 104。逻辑上,t0 = 0和t1 = 0也在第一个循环中。有人可以告诉这个程序有什么问题吗?MIPS回文检查

# 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 

回答

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; 

顺便说一句,一个术语nitpick:# continue recursion。你的实现不是递归的,它是迭代的。