필터 지우기
필터 지우기

write a function called palindrome that takes one input argument a char vector and recursively determine whether that argument is a palindrome you are not allowed to use loops not built in function like srtcmp etc. the function returns true or false

조회 수: 10 (최근 30일)
function ok=palindrome(txt)
iflength(txt)<=1
ok=true;
else
ok=(txt(1)==txt(end)&&palindrome(txt(2:end-1)));
end
end
hi,
It shows error in else statment in the above program, kindly give me a solution to solve the above problem.

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 10월 21일
편집: Ameer Hamza 2020년 10월 21일
There should be a space between if keyword and the condition
if length(txt)<=1
%^ insert a space here
Apart from that, the logic is correct, but you just have a misplaced bracket. Following is correct
ok=(txt(1)==txt(end))&&palindrome(txt(2:end-1));

추가 답변 (3개)

Sandeep Kumar Patel
Sandeep Kumar Patel 2022년 4월 13일
편집: DGM 2024년 1월 10일
If we apply the edits recommended by @Ameer Hamza, we get this:
function ok=palindrome(txt)
if length(txt)<=1 % added space
ok = true;
else
ok = (txt(1)==txt(end)) && palindrome(txt(2:end-1));
% close parentheses --^
end
end
  댓글 수: 1
DGM
DGM 2024년 1월 10일
Editor's note: I added the comments here so that readers know the two lone characters that were actually changed.

댓글을 달려면 로그인하십시오.


Black Woods
Black Woods 2022년 12월 12일
function ans=palindrome(v)
if v(1)==v(end)
ans=true;
if length(v)==1 || length(v)==2
return
else
palindrome(v(2:length(v)-1));
end
else
ans=false;
end
end

Tarun Sangwan
Tarun Sangwan 2024년 3월 27일
function p = palindrome(n)
if length(n)/2<1
p = 2
else
p = n(1) == n(end)
p = [p palindrome(n(2:end-1))]
end
p = ~ismember(0,p)

카테고리

Help CenterFile Exchange에서 Simulink Environment Customization에 대해 자세히 알아보기

제품


릴리스

R2014b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by