How do I check if a number is a palindrome?

2019-01-02 16:35发布

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).

30条回答
只若初见
2楼-- · 2019-01-02 17:15

In Python, there is a fast, iterative way.

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

def palindrome(n):
    return n == reverse(n)

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

查看更多
只若初见
3楼-- · 2019-01-02 17:15

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).

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.

查看更多
笑指拈花
4楼-- · 2019-01-02 17:16

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))
查看更多
零度萤火
5楼-- · 2019-01-02 17:16

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

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");
    }
}
查看更多
与君花间醉酒
6楼-- · 2019-01-02 17:16
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)
查看更多
裙下三千臣
7楼-- · 2019-01-02 17:17

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.

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...

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.

查看更多
登录 后发表回答