我如何检查一个数字是否为回文?

时间:2021-12-10 07:32:53

How do I check if a number is a palindrome?

我如何检查一个数字是否为回文?

Any language. Any algorithm. (except the algorithm of making the number a string and then reversing the string).

任何一种语言。任何算法。(除了让数字为字符串,然后反转字符串的算法)。

48 个解决方案

#1


117  

This is one of the Project Euler problems. When I solved it in Haskell I did exactly what you suggest, convert the number to a String. It's then trivial to check that the string is a pallindrome. If it performs well enough, then why bother making it more complex? Being a pallindrome is a lexical property rather than a mathematical one.

这是一个Project Euler问题。当我在Haskell中解决它时,我按照你的建议,将数字转换为字符串。然后检查字符串是否为pallindrome就很简单了。如果它表现的足够好,那么为什么要让它变得更复杂呢?作为一个pallindrome是一个词汇属性,而不是一个数学属性。

#2


257  

For any given num:

对于任何给定的num:

 n = num;
 rev = 0;
 while (num > 0)
 {
      dig = num % 10;
      rev = rev * 10 + dig;
      num = num / 10;
 }

If n == rev then num is a palindrome:

如果n == rev那么num是一个回文:

cout << "Number " << (n == rev ? "IS" : "IS NOT") << " a palindrome" << endl;

#3


24  

def ReverseNumber(n, partial=0):
    if n == 0:
        return partial
    return ReverseNumber(n // 10, partial * 10 + n % 10)

trial = 123454321    
if ReverseNumber(trial) == trial:
    print("It's a Palindrome!")

Works for integers only. It's unclear from the problem statement if floating point numbers or leading zeros need to be considered.

只适用于整数。如果浮点数或前导零需要被考虑,那么问题语句就不清楚了。

#4


20  

Above most of the answers having a trivial problem is that the int variable possibly might overflow.

上面的大多数答案都有一个小问题,即int变量可能会溢出。

Refer to http://leetcode.com/2012/01/palindrome-number.html

指的是http://leetcode.com/2012/01/palindrome-number.html

boolean isPalindrome(int x) {
    if (x < 0)
        return false;
    int div = 1;
    while (x / div >= 10) {
        div *= 10;
    }
    while (x != 0) {
        int l = x / div;
        int r = x % 10;
        if (l != r)
            return false;
        x = (x % div) / 10;
        div /= 100;
    }
    return true;
}

#5


14  

int is_palindrome(unsigned long orig)
{
  unsigned long reversed = 0, n = orig;

  while (n > 0)
  {
    reversed = reversed * 10 + n % 10;
    n /= 10;
  }

  return orig == reversed;
}

#6


9  

Push each individual digit onto a stack, then pop them off. If it's the same forwards and back, it's a palindrome.

把每个数字都推到堆栈上,然后把它们放掉。如果是相同的前后,那就是回文。

#7


7  

I didn't notice any answers that solved this problem using no extra space, i.e., all solutions I saw either used a string, or another integer to reverse the number, or some other data structures.

我没有注意到任何解决这个问题的答案,没有额外的空间。我看到的所有解决方案都使用了一个字符串,或者另一个整数来反转这个数字,或者其他一些数据结构。

Although languages like Java wrap around on integer overflow, this behavior is undefined in languages like C. [Try reversing 2147483647 (Integer.MAX_VALUE) in Java] Workaround could to be to use a long or something but, stylistically, I don't quite like that approach.

尽管像Java这样的语言会在整数溢出上进行包装,但是这种行为在诸如c语言的语言中是没有定义的。(尝试在Java中使用2147483647 (Integer.MAX_VALUE)),但是在风格上,我不太喜欢这种方法。

Now, the concept of a palindromic number is that the number should read the same forwards and backwards. Great. Using this information, we can compare the first digit and the last digit. Trick is, for the first digit, we need the order of the number. Say, 12321. Dividing this by 10000 would get us the leading 1. The trailing 1 can be retrieved by taking the mod with 10. Now, to reduce this to 232. (12321 % 10000)/10 = (2321)/10 = 232. And now, the 10000 would need to be reduced by a factor of 2. So, now on to the Java code...

现在,回文数的概念是数字应该读相同的前后。太好了。利用这些信息,我们可以比较第一个数字和最后一个数字。技巧是,对于第一个数字,我们需要这个数字的顺序。说,12321。除以10000就能得到1。可以通过使用10的mod来检索尾随1。现在,把它减到232。(12321 % 10000)/10 =(2321)/10 = 232。现在,10000需要减少2倍。那么,现在来看看Java代码…

private static boolean isPalindrome(int n) {
    if (n < 0)
        return false;

    int div = 1;
    // find the divisor
    while (n / div >= 10)
        div *= 10;

    // any number less than 10 is a palindrome
    while (n != 0) {
        int leading = n / div;
        int trailing = n % 10;
        if (leading != trailing)
            return false;

        // % with div gets rid of leading digit
        // dividing result by 10 gets rid of trailing digit
        n = (n % div) / 10;

        // got rid of 2 numbers, update div accordingly
        div /= 100;
    }
    return true;
}

Edited as per Hardik's suggestion to cover the cases where there are zeroes in the number.

按照Hardik的建议编辑,以覆盖在数字中有0的情况。

#8


5  

except making the number a string and then reversing the string.

除了把数字变成一个字符串然后倒转字符串。

Why dismiss that solution? It's easy to implement and readable. If you were asked with no computer at hand whether 2**10-23 is a decimal palindrome, you'd surely test it by writing it out in decimal.

为什么把解决方案吗?它易于实现和可读。如果有人问你,2**10-23是不是一个十进制的回文,你一定要用十进制来测试它。

In Python at least, the slogan 'string operations are slower than arithmetic' is actually false. I compared Smink's arithmetical algorithm to simple string reversal int(str(i)[::-1]). There was no significant difference in speed - it happened string reversal was marginally faster.

至少在Python中,口号“字符串操作比算术慢”实际上是错误的。我将Smink的算术算法与简单的字符串反转int(str(I)[:: 1])进行了比较。在速度上没有显著的差异——发生的字符串反转稍微快一点。

In low level languages (C/C++) the slogan might hold, but one risks overflow errors with large numbers.

在低级别语言(C/ c++)中,口号可能会被保留,但是有一个风险会带来大量的溢出错误。


def reverse(n):
    rev = 0
    while n > 0:
        rev = rev * 10 + n % 10
        n = n // 10
    return rev

upper = 10**6

def strung():
    for i in range(upper):
        int(str(i)[::-1])

def arithmetic():
    for i in range(upper):
        reverse(i)

import timeit
print "strung", timeit.timeit("strung()", setup="from __main__ import strung", number=1)
print "arithmetic", timeit.timeit("arithmetic()", setup="from __main__ import arithmetic", number=1)

Results in seconds (lower is better):

以秒为单位(越低越好):

strung 1.50960231881
arithmetic 1.69729960569

1.50960231881算术1.69729960569串

#9


4  

I answered the Euler problem using a very brute-forcy way. Naturally, there was a much smarter algorithm at display when I got to the new unlocked associated forum thread. Namely, a member who went by the handle Begoner had such a novel approach, that I decided to reimplement my solution using his algorithm. His version was in Python (using nested loops) and I reimplemented it in Clojure (using a single loop/recur).

我用一种非常残忍的方式回答了欧拉问题。自然地,当我到达新打开的关联论坛线程时,有一个更智能的算法在显示。也就是说,一个由句柄开始的成员有这样一种新颖的方法,我决定用他的算法来重新实现我的解决方案。他的版本是在Python中(使用嵌套循环),我在Clojure中重新实现了它(使用一个循环/重复)。

Here for your amusement:

在这里你的娱乐:

(defn palindrome? [n]
  (let [len (count n)]
    (and
      (= (first n) (last n))
      (or (>= 1 (count n))
        (palindrome? (. n (substring 1 (dec len))))))))

(defn begoners-palindrome []
  (loop [mx 0
         mxI 0
         mxJ 0
         i 999
         j 990]
    (if (> i 100)
      (let [product (* i j)]
        (if (and (> product mx) (palindrome? (str product)))
          (recur product i j
            (if (> j 100) i (dec i))
            (if (> j 100) (- j 11) 990))
          (recur mx mxI mxJ
            (if (> j 100) i (dec i))
            (if (> j 100) (- j 11) 990))))
      mx)))

(time (prn (begoners-palindrome)))

There were Common Lisp answers as well, but they were ungrokable to me.

也有一些常见的Lisp答案,但它们对我来说是不受欢迎的。

#10


4  

Just for fun, this one also works.

只是为了好玩,这个也可以。

a = num;
b = 0;
while (a>=b)
{
  if (a == b) return true;
  b = 10 * b + a % 10;
  if (a == b) return true;
  a = a / 10;
}
return false;

#11


4  

Here is an Scheme version that constructs a function that will work against any base. It has a redundancy check: return false quickly if the number is a multiple of the base (ends in 0). And it doesn't rebuild the entire reversed number, only half. That's all we need.

这里是一个Scheme版本,它构造了一个对任何基础都有效的函数。它有一个冗余检查:如果数字是基数的倍数(以0结尾),则返回false,并且它不能重建整个反向数字,只有一半。这就是我们需要的。

(define make-palindrome-tester
   (lambda (base)
     (lambda (n)
       (cond
         ((= 0 (modulo n base)) #f)
         (else
          (letrec
              ((Q (lambda (h t)
                    (cond
                      ((< h t) #f)
                      ((= h t) #t)
                      (else
                       (let* 
                           ((h2 (quotient h base))
                            (m  (- h (* h2 base))))
                         (cond 
                           ((= h2 t) #t)
                           (else
                            (Q h2 (+ (* base t) m))))))))))           
            (Q n 0)))))))

#12


4  

In Python, there is a fast, iterative way.

在Python中,有一种快速、迭代的方法。

def palindrome(n):
    newnum=0
    while n>0:
        newnum = newnum*10 + n % 10
        n//=10
    return newnum == n

This also prevents memory issues with recursion (like * error in Java)

这还可以防止递归(比如Java中的*错误)的内存问题。

#13


4  

Fastest way I know:

最快的方法我知道:

bool is_pal(int n) {
  if (n % 10 == 0) return 0;
  int r = 0;
  while (r < n) {
    r = 10 * r + n % 10;
    n /= 10;
  }
  return n == r || n == r / 10;
}

#14


3  

Golang version:

Golang版本:

package main

import "fmt"

func main() {
    n := 123454321
    r := reverse(n)
    fmt.Println(r == n)
}

func reverse(n int) int {
    r := 0
    for {
        if n > 0 {
            r = r*10 + n%10         
            n = n / 10
        } else {
            break
        }
    }
    return r
}

#15


3  

Recursive solution in ruby, without converting the number to string

在ruby中递归解决方案,不需要将数字转换为字符串。

def palindrome?(x, a=x, b=0)
  return x==b if a<1
  palindrome?(x, a/10, b*10 + a%10)
end

palindrome?(55655)

#16


2  

Pop off the first and last digits and compare them until you run out. There may be a digit left, or not, but either way, if all the popped off digits match, it is a palindrome.

把第一个和最后一个数字去掉,然后比较它们,直到你用完为止。可能有一个数字向左,或者没有,但不管怎样,如果所有的弹出的数字匹配,它是一个回文。

#17


2  

Here is one more solution in c++ using templates . This solution will work for case insensitive palindrome string comparison .

这里还有一个使用模板的c++解决方案。此解决方案将用于大小写不敏感的回文字符串比较。

template <typename bidirection_iter>
bool palindrome(bidirection_iter first, bidirection_iter last)
{
    while(first != last && first != --last)
    {
        if(::toupper(*first) != ::toupper(*last))
            return false;
        else
            first++;
    }
    return true;
}

#18


1  

a method with a little better constant factor than @sminks method:

一种比@sminks方法稍微好一点的方法:

num=n
lastDigit=0;
rev=0;
while (num>rev) {
    lastDigit=num%10;
    rev=rev*10+lastDigit;
    num /=2;
}
if (num==rev) print PALINDROME; exit(0);
num=num*10+lastDigit; // This line is required as a number with odd number of bits will necessary end up being smaller even if it is a palindrome
if (num==rev) print PALINDROME

#19


1  

here's a f# version:

这里有一个f#版本:

let reverseNumber n =
    let rec loop acc = function
    |0 -> acc
    |x -> loop (acc * 10 + x % 10) (x/10)    
    loop 0 n

let isPalindrome = function
    | x  when x = reverseNumber x -> true
    | _ -> false

#20


1  

A number is palindromic if its string representation is palindromic:

一个数字是回文,如果它的字符串表示是回文:

def is_palindrome(s):
    return all(s[i] == s[-(i + 1)] for i in range(len(s)//2))

def number_palindrome(n):
    return is_palindrome(str(n))

#21


1  

def palindrome(n):
    d = []
    while (n > 0):
        d.append(n % 10)
        n //= 10
    for i in range(len(d)/2):
        if (d[i] != d[-(i+1)]):
            return "Fail."
    return "Pass."

#22


1  

To check the given number is Palindrome or not (Java Code)

检查给定的数字是否为回文(Java代码)

class CheckPalindrome{
public static void main(String str[]){
        int a=242, n=a, b=a, rev=0;
        while(n>0){
                    a=n%10;  n=n/10;rev=rev*10+a;
                    System.out.println(a+"  "+n+"  "+rev);  // to see the logic
               }
        if(rev==b)  System.out.println("Palindrome");
        else        System.out.println("Not Palindrome");
    }
}

#23


1  

A lot of the solutions posted here reverses the integer and stores it in a variable which uses extra space which is O(n), but here is a solution with O(1) space.

在这里发布的许多解决方案都将这个整数颠倒过来,并将其存储在一个变量中,该变量使用的是O(n)的额外空间,但这里是一个带有O(1)空间的解决方案。

def isPalindrome(num):
    if num < 0:
        return False
    if num == 0:
        return True
    from math import log10
    length = int(log10(num))
    while length > 0:
        right = num % 10
        left = num / 10**length
        if right != left:
            return False
        num %= 10**length
        num /= 10
        length -= 2
    return True

#24


1  

I always use this python solution due to its compactness.

我总是使用这个python解决方案,因为它的紧凑性。

def isPalindrome(number):
    return int(str(number)[::-1])==number

#25


0  

Try this:

试试这个:

reverse = 0;
    remainder = 0;
    count = 0;
    while (number > reverse)
    {
        remainder = number % 10;
        reverse = reverse * 10 + remainder;
        number = number / 10;
        count++;
    }
    Console.WriteLine(count);
    if (reverse == number)
    {
        Console.WriteLine("Your number is a palindrome");
    }
    else
    {
        number = number * 10 + remainder;
        if (reverse == number)
            Console.WriteLine("your number is a palindrome");
        else
            Console.WriteLine("your number is not a palindrome");
    }
    Console.ReadLine();
}
}

#26


0  

Here is a solution usings lists as stacks in python :

这里有一个解决方案,在python中作为堆栈列表:

def isPalindromicNum(n):
    """
        is 'n' a palindromic number?
    """
    ns = list(str(n))
    for n in ns:
        if n != ns.pop():
            return False
    return True

popping the stack only considers the rightmost side of the number for comparison and it fails fast to reduce checks

弹出堆栈只考虑数字的最右边,而它不能快速地减少检查。

#27


0  

 public class Numbers
 {
   public static void main(int givenNum)
   { 
       int n= givenNum
       int rev=0;

       while(n>0)
       {
          //To extract the last digit
          int digit=n%10;

          //To store it in reverse
          rev=(rev*10)+digit;

          //To throw the last digit
          n=n/10;
      }

      //To check if a number is palindrome or not
      if(rev==givenNum)
      { 
         System.out.println(givenNum+"is a palindrome ");
      }
      else
      {
         System.out.pritnln(givenNum+"is not a palindrome");
      }
  }
}

#28


0  

let isPalindrome (n:int) =
   let l1 = n.ToString() |> List.ofSeq |> List.rev
   let rec isPalindromeInt l1 l2 =
       match (l1,l2) with
       | (h1::rest1,h2::rest2) -> if (h1 = h2) then isPalindromeInt rest1 rest2 else false
       | _ -> true
   isPalindromeInt l1 (n.ToString() |> List.ofSeq)

#29


0  

checkPalindrome(int number)
{
    int lsd, msd,len;
    len = log10(number);
    while(number)
    {
        msd = (number/pow(10,len)); // "most significant digit"
        lsd = number%10; // "least significant digit"
        if(lsd==msd)
        {
            number/=10; // change of LSD
            number-=msd*pow(10,--len); // change of MSD, due to change of MSD
            len-=1; // due to change in LSD
            } else {return 1;}
    }
    return 0;
}

#30


0  

Recursive way, not very efficient, just provide an option

递归方式,不是很高效,只是提供一个选项。

(Python code)

(Python代码)

def isPalindrome(num):
    size = len(str(num))
    demoninator = 10**(size-1)
    return isPalindromeHelper(num, size, demoninator)

def isPalindromeHelper(num, size, demoninator):
    """wrapper function, used in recursive"""
    if size <=1:
        return True
    else:       
        if num/demoninator != num%10:
            return False
        # shrink the size, num and denominator
        num %= demoninator
        num /= 10
        size -= 2
        demoninator /=100
        return isPalindromeHelper(num, size, demoninator) 

#1


117  

This is one of the Project Euler problems. When I solved it in Haskell I did exactly what you suggest, convert the number to a String. It's then trivial to check that the string is a pallindrome. If it performs well enough, then why bother making it more complex? Being a pallindrome is a lexical property rather than a mathematical one.

这是一个Project Euler问题。当我在Haskell中解决它时,我按照你的建议,将数字转换为字符串。然后检查字符串是否为pallindrome就很简单了。如果它表现的足够好,那么为什么要让它变得更复杂呢?作为一个pallindrome是一个词汇属性,而不是一个数学属性。

#2


257  

For any given num:

对于任何给定的num:

 n = num;
 rev = 0;
 while (num > 0)
 {
      dig = num % 10;
      rev = rev * 10 + dig;
      num = num / 10;
 }

If n == rev then num is a palindrome:

如果n == rev那么num是一个回文:

cout << "Number " << (n == rev ? "IS" : "IS NOT") << " a palindrome" << endl;

#3


24  

def ReverseNumber(n, partial=0):
    if n == 0:
        return partial
    return ReverseNumber(n // 10, partial * 10 + n % 10)

trial = 123454321    
if ReverseNumber(trial) == trial:
    print("It's a Palindrome!")

Works for integers only. It's unclear from the problem statement if floating point numbers or leading zeros need to be considered.

只适用于整数。如果浮点数或前导零需要被考虑,那么问题语句就不清楚了。

#4


20  

Above most of the answers having a trivial problem is that the int variable possibly might overflow.

上面的大多数答案都有一个小问题,即int变量可能会溢出。

Refer to http://leetcode.com/2012/01/palindrome-number.html

指的是http://leetcode.com/2012/01/palindrome-number.html

boolean isPalindrome(int x) {
    if (x < 0)
        return false;
    int div = 1;
    while (x / div >= 10) {
        div *= 10;
    }
    while (x != 0) {
        int l = x / div;
        int r = x % 10;
        if (l != r)
            return false;
        x = (x % div) / 10;
        div /= 100;
    }
    return true;
}

#5


14  

int is_palindrome(unsigned long orig)
{
  unsigned long reversed = 0, n = orig;

  while (n > 0)
  {
    reversed = reversed * 10 + n % 10;
    n /= 10;
  }

  return orig == reversed;
}

#6


9  

Push each individual digit onto a stack, then pop them off. If it's the same forwards and back, it's a palindrome.

把每个数字都推到堆栈上,然后把它们放掉。如果是相同的前后,那就是回文。

#7


7  

I didn't notice any answers that solved this problem using no extra space, i.e., all solutions I saw either used a string, or another integer to reverse the number, or some other data structures.

我没有注意到任何解决这个问题的答案,没有额外的空间。我看到的所有解决方案都使用了一个字符串,或者另一个整数来反转这个数字,或者其他一些数据结构。

Although languages like Java wrap around on integer overflow, this behavior is undefined in languages like C. [Try reversing 2147483647 (Integer.MAX_VALUE) in Java] Workaround could to be to use a long or something but, stylistically, I don't quite like that approach.

尽管像Java这样的语言会在整数溢出上进行包装,但是这种行为在诸如c语言的语言中是没有定义的。(尝试在Java中使用2147483647 (Integer.MAX_VALUE)),但是在风格上,我不太喜欢这种方法。

Now, the concept of a palindromic number is that the number should read the same forwards and backwards. Great. Using this information, we can compare the first digit and the last digit. Trick is, for the first digit, we need the order of the number. Say, 12321. Dividing this by 10000 would get us the leading 1. The trailing 1 can be retrieved by taking the mod with 10. Now, to reduce this to 232. (12321 % 10000)/10 = (2321)/10 = 232. And now, the 10000 would need to be reduced by a factor of 2. So, now on to the Java code...

现在,回文数的概念是数字应该读相同的前后。太好了。利用这些信息,我们可以比较第一个数字和最后一个数字。技巧是,对于第一个数字,我们需要这个数字的顺序。说,12321。除以10000就能得到1。可以通过使用10的mod来检索尾随1。现在,把它减到232。(12321 % 10000)/10 =(2321)/10 = 232。现在,10000需要减少2倍。那么,现在来看看Java代码…

private static boolean isPalindrome(int n) {
    if (n < 0)
        return false;

    int div = 1;
    // find the divisor
    while (n / div >= 10)
        div *= 10;

    // any number less than 10 is a palindrome
    while (n != 0) {
        int leading = n / div;
        int trailing = n % 10;
        if (leading != trailing)
            return false;

        // % with div gets rid of leading digit
        // dividing result by 10 gets rid of trailing digit
        n = (n % div) / 10;

        // got rid of 2 numbers, update div accordingly
        div /= 100;
    }
    return true;
}

Edited as per Hardik's suggestion to cover the cases where there are zeroes in the number.

按照Hardik的建议编辑,以覆盖在数字中有0的情况。

#8


5  

except making the number a string and then reversing the string.

除了把数字变成一个字符串然后倒转字符串。

Why dismiss that solution? It's easy to implement and readable. If you were asked with no computer at hand whether 2**10-23 is a decimal palindrome, you'd surely test it by writing it out in decimal.

为什么把解决方案吗?它易于实现和可读。如果有人问你,2**10-23是不是一个十进制的回文,你一定要用十进制来测试它。

In Python at least, the slogan 'string operations are slower than arithmetic' is actually false. I compared Smink's arithmetical algorithm to simple string reversal int(str(i)[::-1]). There was no significant difference in speed - it happened string reversal was marginally faster.

至少在Python中,口号“字符串操作比算术慢”实际上是错误的。我将Smink的算术算法与简单的字符串反转int(str(I)[:: 1])进行了比较。在速度上没有显著的差异——发生的字符串反转稍微快一点。

In low level languages (C/C++) the slogan might hold, but one risks overflow errors with large numbers.

在低级别语言(C/ c++)中,口号可能会被保留,但是有一个风险会带来大量的溢出错误。


def reverse(n):
    rev = 0
    while n > 0:
        rev = rev * 10 + n % 10
        n = n // 10
    return rev

upper = 10**6

def strung():
    for i in range(upper):
        int(str(i)[::-1])

def arithmetic():
    for i in range(upper):
        reverse(i)

import timeit
print "strung", timeit.timeit("strung()", setup="from __main__ import strung", number=1)
print "arithmetic", timeit.timeit("arithmetic()", setup="from __main__ import arithmetic", number=1)

Results in seconds (lower is better):

以秒为单位(越低越好):

strung 1.50960231881
arithmetic 1.69729960569

1.50960231881算术1.69729960569串

#9


4  

I answered the Euler problem using a very brute-forcy way. Naturally, there was a much smarter algorithm at display when I got to the new unlocked associated forum thread. Namely, a member who went by the handle Begoner had such a novel approach, that I decided to reimplement my solution using his algorithm. His version was in Python (using nested loops) and I reimplemented it in Clojure (using a single loop/recur).

我用一种非常残忍的方式回答了欧拉问题。自然地,当我到达新打开的关联论坛线程时,有一个更智能的算法在显示。也就是说,一个由句柄开始的成员有这样一种新颖的方法,我决定用他的算法来重新实现我的解决方案。他的版本是在Python中(使用嵌套循环),我在Clojure中重新实现了它(使用一个循环/重复)。

Here for your amusement:

在这里你的娱乐:

(defn palindrome? [n]
  (let [len (count n)]
    (and
      (= (first n) (last n))
      (or (>= 1 (count n))
        (palindrome? (. n (substring 1 (dec len))))))))

(defn begoners-palindrome []
  (loop [mx 0
         mxI 0
         mxJ 0
         i 999
         j 990]
    (if (> i 100)
      (let [product (* i j)]
        (if (and (> product mx) (palindrome? (str product)))
          (recur product i j
            (if (> j 100) i (dec i))
            (if (> j 100) (- j 11) 990))
          (recur mx mxI mxJ
            (if (> j 100) i (dec i))
            (if (> j 100) (- j 11) 990))))
      mx)))

(time (prn (begoners-palindrome)))

There were Common Lisp answers as well, but they were ungrokable to me.

也有一些常见的Lisp答案,但它们对我来说是不受欢迎的。

#10


4  

Just for fun, this one also works.

只是为了好玩,这个也可以。

a = num;
b = 0;
while (a>=b)
{
  if (a == b) return true;
  b = 10 * b + a % 10;
  if (a == b) return true;
  a = a / 10;
}
return false;

#11


4  

Here is an Scheme version that constructs a function that will work against any base. It has a redundancy check: return false quickly if the number is a multiple of the base (ends in 0). And it doesn't rebuild the entire reversed number, only half. That's all we need.

这里是一个Scheme版本,它构造了一个对任何基础都有效的函数。它有一个冗余检查:如果数字是基数的倍数(以0结尾),则返回false,并且它不能重建整个反向数字,只有一半。这就是我们需要的。

(define make-palindrome-tester
   (lambda (base)
     (lambda (n)
       (cond
         ((= 0 (modulo n base)) #f)
         (else
          (letrec
              ((Q (lambda (h t)
                    (cond
                      ((< h t) #f)
                      ((= h t) #t)
                      (else
                       (let* 
                           ((h2 (quotient h base))
                            (m  (- h (* h2 base))))
                         (cond 
                           ((= h2 t) #t)
                           (else
                            (Q h2 (+ (* base t) m))))))))))           
            (Q n 0)))))))

#12


4  

In Python, there is a fast, iterative way.

在Python中,有一种快速、迭代的方法。

def palindrome(n):
    newnum=0
    while n>0:
        newnum = newnum*10 + n % 10
        n//=10
    return newnum == n

This also prevents memory issues with recursion (like * error in Java)

这还可以防止递归(比如Java中的*错误)的内存问题。

#13


4  

Fastest way I know:

最快的方法我知道:

bool is_pal(int n) {
  if (n % 10 == 0) return 0;
  int r = 0;
  while (r < n) {
    r = 10 * r + n % 10;
    n /= 10;
  }
  return n == r || n == r / 10;
}

#14


3  

Golang version:

Golang版本:

package main

import "fmt"

func main() {
    n := 123454321
    r := reverse(n)
    fmt.Println(r == n)
}

func reverse(n int) int {
    r := 0
    for {
        if n > 0 {
            r = r*10 + n%10         
            n = n / 10
        } else {
            break
        }
    }
    return r
}

#15


3  

Recursive solution in ruby, without converting the number to string

在ruby中递归解决方案,不需要将数字转换为字符串。

def palindrome?(x, a=x, b=0)
  return x==b if a<1
  palindrome?(x, a/10, b*10 + a%10)
end

palindrome?(55655)

#16


2  

Pop off the first and last digits and compare them until you run out. There may be a digit left, or not, but either way, if all the popped off digits match, it is a palindrome.

把第一个和最后一个数字去掉,然后比较它们,直到你用完为止。可能有一个数字向左,或者没有,但不管怎样,如果所有的弹出的数字匹配,它是一个回文。

#17


2  

Here is one more solution in c++ using templates . This solution will work for case insensitive palindrome string comparison .

这里还有一个使用模板的c++解决方案。此解决方案将用于大小写不敏感的回文字符串比较。

template <typename bidirection_iter>
bool palindrome(bidirection_iter first, bidirection_iter last)
{
    while(first != last && first != --last)
    {
        if(::toupper(*first) != ::toupper(*last))
            return false;
        else
            first++;
    }
    return true;
}

#18


1  

a method with a little better constant factor than @sminks method:

一种比@sminks方法稍微好一点的方法:

num=n
lastDigit=0;
rev=0;
while (num>rev) {
    lastDigit=num%10;
    rev=rev*10+lastDigit;
    num /=2;
}
if (num==rev) print PALINDROME; exit(0);
num=num*10+lastDigit; // This line is required as a number with odd number of bits will necessary end up being smaller even if it is a palindrome
if (num==rev) print PALINDROME

#19


1  

here's a f# version:

这里有一个f#版本:

let reverseNumber n =
    let rec loop acc = function
    |0 -> acc
    |x -> loop (acc * 10 + x % 10) (x/10)    
    loop 0 n

let isPalindrome = function
    | x  when x = reverseNumber x -> true
    | _ -> false

#20


1  

A number is palindromic if its string representation is palindromic:

一个数字是回文,如果它的字符串表示是回文:

def is_palindrome(s):
    return all(s[i] == s[-(i + 1)] for i in range(len(s)//2))

def number_palindrome(n):
    return is_palindrome(str(n))

#21


1  

def palindrome(n):
    d = []
    while (n > 0):
        d.append(n % 10)
        n //= 10
    for i in range(len(d)/2):
        if (d[i] != d[-(i+1)]):
            return "Fail."
    return "Pass."

#22


1  

To check the given number is Palindrome or not (Java Code)

检查给定的数字是否为回文(Java代码)

class CheckPalindrome{
public static void main(String str[]){
        int a=242, n=a, b=a, rev=0;
        while(n>0){
                    a=n%10;  n=n/10;rev=rev*10+a;
                    System.out.println(a+"  "+n+"  "+rev);  // to see the logic
               }
        if(rev==b)  System.out.println("Palindrome");
        else        System.out.println("Not Palindrome");
    }
}

#23


1  

A lot of the solutions posted here reverses the integer and stores it in a variable which uses extra space which is O(n), but here is a solution with O(1) space.

在这里发布的许多解决方案都将这个整数颠倒过来,并将其存储在一个变量中,该变量使用的是O(n)的额外空间,但这里是一个带有O(1)空间的解决方案。

def isPalindrome(num):
    if num < 0:
        return False
    if num == 0:
        return True
    from math import log10
    length = int(log10(num))
    while length > 0:
        right = num % 10
        left = num / 10**length
        if right != left:
            return False
        num %= 10**length
        num /= 10
        length -= 2
    return True

#24


1  

I always use this python solution due to its compactness.

我总是使用这个python解决方案,因为它的紧凑性。

def isPalindrome(number):
    return int(str(number)[::-1])==number

#25


0  

Try this:

试试这个:

reverse = 0;
    remainder = 0;
    count = 0;
    while (number > reverse)
    {
        remainder = number % 10;
        reverse = reverse * 10 + remainder;
        number = number / 10;
        count++;
    }
    Console.WriteLine(count);
    if (reverse == number)
    {
        Console.WriteLine("Your number is a palindrome");
    }
    else
    {
        number = number * 10 + remainder;
        if (reverse == number)
            Console.WriteLine("your number is a palindrome");
        else
            Console.WriteLine("your number is not a palindrome");
    }
    Console.ReadLine();
}
}

#26


0  

Here is a solution usings lists as stacks in python :

这里有一个解决方案,在python中作为堆栈列表:

def isPalindromicNum(n):
    """
        is 'n' a palindromic number?
    """
    ns = list(str(n))
    for n in ns:
        if n != ns.pop():
            return False
    return True

popping the stack only considers the rightmost side of the number for comparison and it fails fast to reduce checks

弹出堆栈只考虑数字的最右边,而它不能快速地减少检查。

#27


0  

 public class Numbers
 {
   public static void main(int givenNum)
   { 
       int n= givenNum
       int rev=0;

       while(n>0)
       {
          //To extract the last digit
          int digit=n%10;

          //To store it in reverse
          rev=(rev*10)+digit;

          //To throw the last digit
          n=n/10;
      }

      //To check if a number is palindrome or not
      if(rev==givenNum)
      { 
         System.out.println(givenNum+"is a palindrome ");
      }
      else
      {
         System.out.pritnln(givenNum+"is not a palindrome");
      }
  }
}

#28


0  

let isPalindrome (n:int) =
   let l1 = n.ToString() |> List.ofSeq |> List.rev
   let rec isPalindromeInt l1 l2 =
       match (l1,l2) with
       | (h1::rest1,h2::rest2) -> if (h1 = h2) then isPalindromeInt rest1 rest2 else false
       | _ -> true
   isPalindromeInt l1 (n.ToString() |> List.ofSeq)

#29


0  

checkPalindrome(int number)
{
    int lsd, msd,len;
    len = log10(number);
    while(number)
    {
        msd = (number/pow(10,len)); // "most significant digit"
        lsd = number%10; // "least significant digit"
        if(lsd==msd)
        {
            number/=10; // change of LSD
            number-=msd*pow(10,--len); // change of MSD, due to change of MSD
            len-=1; // due to change in LSD
            } else {return 1;}
    }
    return 0;
}

#30


0  

Recursive way, not very efficient, just provide an option

递归方式,不是很高效,只是提供一个选项。

(Python code)

(Python代码)

def isPalindrome(num):
    size = len(str(num))
    demoninator = 10**(size-1)
    return isPalindromeHelper(num, size, demoninator)

def isPalindromeHelper(num, size, demoninator):
    """wrapper function, used in recursive"""
    if size <=1:
        return True
    else:       
        if num/demoninator != num%10:
            return False
        # shrink the size, num and denominator
        num %= demoninator
        num /= 10
        size -= 2
        demoninator /=100
        return isPalindromeHelper(num, size, demoninator)