2014-11-04 2 views
1

입력 문자열이 palindrome인지 확인하는 MIPS 프로그램을 작성하려고합니다. 필자는 문자열 "HelllleH"를 테스트했으며 프로그램을 단계별로 실행할 때 PAL_CHECK t0 = 0이지만 t1 = 104의 첫 번째 루프에서이를 보았습니다. 논리적으로 첫 번째 루프에서도 t0 = 0 및 t1 = 0이었습니다. 누군가이 프로그램에서 잘못된 점을 말할 수 있습니까? 문자열의 길이를 찾는 동안MIPS Palindrome Check

# 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

당신은 지속적으로 당신이 문자열의 끝에 NUL 종료를 찾을 때까지 다음 문자를 가리 키도록 $a0를 증가. palindrome 체크 루프 전에 $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. 귀하의 구현은 재귀 적이 아니며 반복적입니다.