在shell脚本中编写一个函数来检查两个数字是否是回文

问题描述

我正在用 shell 脚本编写一个函数来检查这两个数字是否是回文,但我收到一个错误,它在第 18 行命令中显示错误未找到。请帮助我如何消除此错误。 #!/bin/bash

echo "Enter two number:"
read a
read b
for num in $a $b;
do
    x=$x$sep$num
    sep=" "
done
y=$x
num1=$a
num2=$b
rem=""
rev=0
for word in $y;
do
checkpalindrome $word
if [ $? -eq 0 ]
then
echo "$word is palindrome"
fi
done
checkpalindrome() {
local s=$1
for i in $s ;
do
while [ $i -gt 0]
do
rem=$(($i%10));
rev=$(($rev*10+$rem));
i=$(($i / 10));
done
done

if [[ $rev -eq $num1 && $rev -eq $num2  ]]
then
return 0;
else
return 1;
fi
}

解决方法

您需要在使用之前提供您的 checkPalindrome() 定义,如下所示:

#!/bin/bash

checkPalindrome() {
    local s=$1

    for i in $s
    do
        while [ "$i" -gt 0 ]
        do
            rem=$((i%10))
            rev=$((rev*10+rem))
            i=$((i / 10))
        done
    done

    if [[ $rev -eq $num1 && $rev -eq $num2 ]]
    then
        return 0
    else
        return 1
    fi
}

echo "Enter two number:"
read -r a
read -r b

for num in $a $b
do
    x="$x$sep$num"
    sep=" "
done

y="$x"
num1="$a"
num2="$b"
rem=""
rev=0
for word in $y;
do
    if checkPalindrome "$word"
    then
        echo "$word is palindrome"
    fi
done
,

您可以将输入视为字符串(您不必将其限制为整数)

#!/bin/bash

is_palindrome() {
    local arg=$1 i j
    for ((i = 0,j = ${#arg} - 1; i < j; ++i,--j)); do
        [[ ${arg:i:1} = "${arg:j:1}" ]] || return
    done
}

read -r -p 'Enter two words: ' a b
for word in $a $b; do
    is_palindrome "$word" && echo "$word is palindrome"
done