简体   繁体   English

如何在 Clean 中检查数字是否为回文

[英]How to check if a number is palindrome in Clean

I am solving this homework of clean programming language;我正在解决这个干净的编程语言的作业; The problem is we have a number of five digits and we want to check whether it's an odd palindrome or not.问题是我们有一个五位数的数字,我们想检查它是否是奇数回文。 I am stuck at the stage of dividing the number to five separate digits and perform a comparison with the original number, for the palindrome check.我停留在将数字分成五个独立数字并与原始数字进行比较以进行回文检查的阶段。 With Clean I can't loop over the number and check if it remains the same from the both sides, so I am looking for an alternative solution (Some mathematical operations).使用 Clean 我无法遍历数字并检查它是否从两侧保持不变,所以我正在寻找替代解决方案(一些数学运算)。

Code block:代码块:

isOddPalindrome :: Int -> Bool
isOddPalindrome a
| isFive a <> 5 = abort("The number should be exactly five digits...")
| (/*==> Here should be the palindrome check <==*/) && (a rem 2 <> 0) = True
| otherwise = False

isFive :: Int -> Int
isFive n
| n / 10 == 0 = 1
= 1 + isFive(n / 10)

My idea is to take the number, append it's digits one by one to an empty list, then perform the reverse method on the list and check if it's the same number or not (Palindrome)我的想法是将数字 append 的数字一位一位地取到一个空列表中,然后在列表上执行reverse方法并检查它是否相同(回文)

Your answer above doesn't have a stopping condition so it will result in stack overflow.您上面的答案没有停止条件,因此会导致堆栈溢出。

You could try this你可以试试这个

numToList :: Int -> [Int]
numToList n
| n < 10 = [n]
= numToList (n/10) ++ [n rem 10]

Start = numToList 12345

and then like you mentioned in the answer, you can reverse it with the 'reverse' function and check if they are equal.然后就像你在答案中提到的那样,你可以用'reverse' function 反转它并检查它们是否相等。

After hours of trying to figure out how to recursively add the digits of our number to an empty list, I did the following:经过数小时的尝试找出如何递归地将我们的数字添加到空列表后,我做了以下事情:

sepDigits :: Int [Int] -> [Int]
sepDigits n x = sepDigits (n/10) [n rem 10 : x]

Now I can easily check whether the reverse is equal to the initial list:) then the number is palindrome.现在我可以很容易地检查反向是否等于初始列表:)那么这个数字就是回文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM