【问题标题】:How do I check if a number is a palindrome?如何检查一个数字是否是回文?
【发布时间】:2010-09-16 23:37:26
【问题描述】:

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

任何语言。任何算法。 (除了将数字变成字符串然后反转字符串的算法)。

【问题讨论】:

  • 你能找出整数的大小吗?如果是,则说 A 是否,s 是大小 B = A
  • “将数字变为字符串然后反转字符串”有什么问题?
  • 首先定义numberis a palindrome 在这种情况下的含义:13E31(以十为基数)怎么样? 01210(前导零)? +10-10+1(五位平衡三进制)?

标签: algorithm language-agnostic


【解决方案1】:

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
}

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 关闭,但您在执行此操作时正在改变 n。您想存储原始 n 值并使用它进行返回比较
    【解决方案3】:

    我知道的最快方法:

    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;
    }
    

    【讨论】:

    【解决方案4】:
    num = int(raw_input())
    list_num = list(str(num))
    if list_num[::-1] == list_num:
        print "Its a palindrome"
    else:
        print "Its not a palindrom"
    

    【讨论】:

      【解决方案5】:

      不确定这是否是最佳答案,而且我是编程新手。 (它在java中)

      import java.util.*;
      
      public class Palin {
      
          public static void main(String[] args) {
              Random randInt = new Random();
      
              Scanner kbd = new Scanner(System.in);
              int t = kbd.nextInt(); //# of test cases;
              String[] arrPalin = new String[t]; //array of inputs;
              String[] nextPalin = new String[t];
              for (int i = 0; i < t; i++) {
                  arrPalin[i] = String.valueOf(randInt.nextInt(2147483646) + 1);
                  System.out.println(arrPalin[i]);
              }
      
              final long startTime = System.nanoTime();
      
              for (int i = 0; i < t; i++) {
                  nextPalin[i] = (unmatcher(incrementer(switcher(match(arrPalin[i])))));
              }
      
              final long duration = System.nanoTime() - startTime;
      
              for (int i = 0; i < t; i++) {
                  System.out.println(nextPalin[i]);
              }
      
              System.out.println(duration);
      
          }
      
          public static String match(String N) {
              int length = N.length();
      
              //Initialize a string with length of N
              char[] chars = new char[length];
              Arrays.fill(chars, '0');
      
              int count = 1;
      
              for (int i = 0; i < length; i++) {
                  if ((i%2) == 0) { //at i = even.
                      if (i == 0) {
                          chars[i] = N.charAt(i);
                      } else
                          chars[i] = N.charAt(i/2);
                  } else //at i = odd
                      chars[i] = N.charAt(length - count);
                      count++;
              }
      
              return String.valueOf(chars);
          }
      
          public static String switcher(String N) {
              int length = N.length();
              char[] chars = new char[length];
              Arrays.fill(chars, '0');
      
              for (int i = 0; i < length; i++) {
                  if (i != 0) {
                      if ((i % 2) == 0) {
                          chars[i] = N.charAt(i);
                      } else if ((i % 2) != 0) {
                          chars[i] = N.charAt(i - 1);
                      }
                  }
                  if (i == 0) {
                      chars[0] = N.charAt(0);
                  }
              }
              return String.valueOf(chars);
          }
      
          public static String incrementer(String N) {
              int length = N.length();
              char[] chars = new char[length];
              Arrays.fill(chars, '0');
      
              char[] newN = N.toCharArray();
      
              String returnVal;
      
              int numOne, numTwo;
      
              if ((length % 2) == 0) {
                  numOne = N.charAt(length-1);
                  numTwo = N.charAt(length-2);
                  newN[length-1] = (char)(numOne+1);
                  newN[length-2] = (char)(numTwo+1);
                  returnVal = String.valueOf(newN);
              } else {
                  numOne = N.charAt(length-1);
                  newN[length-1] = (char)(numOne+1);
                  returnVal = String.valueOf(newN);
              }
              return returnVal;
          }
      
          public static String unmatcher(String N) {
              int length = N.length();
              char[] chars = new char[length];
              Arrays.fill(chars, '0');
              char[] newN = N.toCharArray();
      
              for (int i = 0; i < length; i++) {
                      if (((i % 2) == 0) && (i != 0)) { // for i > 0, even
                          newN[i / 2] = N.charAt(i);
                      } else if ((i % 2) == 0 && (i == 0)) { // for i = 0
                          newN[0] = N.charAt(0);
                      }
                  }
              for (int i = (length/2); i < length; i++) {
                  newN[i] = newN[Math.abs(i - (length - 1))];
              }
      
              return String.valueOf(newN);
          }
      
      
      }
      

      所以对于这段代码,输入一个数字(我做了我想要多少的随机数), 它将转换,例如输入是 172345 到 157423。然后它会将其更改为 117722,然后如果偶数将其变为 117733,如果奇数则对最后一位数字执行相同操作。然后将其设为 173371。它不是专门查找回文数,而是查找下一个最高的回文数。

      【讨论】:

        【解决方案6】:
        public class PalindromePrime   {
             private static int g ,n =0,i,m ; 
             
             private javax.swing.JTextField jTextField;
             
        
             static String b ="";
            private static Scanner scanner = new Scanner( System.in );  
            public static void main(String [] args) throws IOException {
                System.out.print(" Please Inter Data : "); 
                g = scanner.nextInt();
                
                System.out.print(" Please Inter Data 2  : "); 
                m = scanner.nextInt();  
                
                count(g,m);     
            }   
        
            public static    int count(int L, int R) {
                int resultNum = 0;
            
                for( i= L ; i<= R ;i++){
                    int count= 0 ;
                    for( n = i ; n >=1 ;n -- ){
                        if(i%n==0){             
                            count = count + 1 ;
                        //  System.out.println("  Data : \n "  +count );    
                        }       
                    }
                    if(count == 2)
                    {   
                        //b = b +i + "" ;
                        
                    String ss=  String .valueOf(i);
                    //  System.out.print("\n" +i );
                        if(isPalindrome(i))
                        {
                        //0 System.out.println("Number : " + i + " is   a palindrome");
                        
                                //number2[b] = Integer.parseInt(number_ayy[b]);
                                
                            //String s = String .valueOf(i);
                            //System.out.printf("123456", s);
                            resultNum++;
                        }
                        else{
                            //*System.out.println("Number : " + i + " is Not  a palindrome");
                        }
                        //System.out.println("  Data : \n " +ss.length()  );    
                    }
                //  palindrome(i);
                }
                
            //  System.out.print("  Data  : "); 
            //  System.out.println("  Data : \n "  +b ); 
                return resultNum;
            }
            
            @SuppressWarnings("unused")
            public static boolean isPalindrome(int number  ) {
                int p = number; // ประกาศ  p เป็น int ให้เท่ากับ number ของ ตัวที่ มาจาก method 
                int r = 0; //ประกาศ r เป็น int โดยให้มีค่าเรื่องต้นเท่ากับ 0 
                int w = 0 ;
                while (p != 0) {  // เงื่อนไข While ถ้า p ไม่เท่ากับ 0  เช่น  2!= 0 จริง  เข้า  
                     w = p % 10; // ประกาศตัว แปร W ให้ เท่ากับค่า p ที่มาจาก parramiter ให้ & mod กับ  10 คือ เช่น  2 % 10 = 2 ; w= 2 ; 3% 10 ; w =3
                   r = r * 10 + w;  // (ให้  R ที่มาจาก การประกาศค่ตัวแปร แล้ว * 10) + w  จะมาจากค่า w = p % 10; ที่ mod ไว้  เช่น 0*10 + 2 = 2 
                   p = p / 10;  //แล้วใช้ p ที่จมาจากตัว paramiter แล้วมาหาร  10  เพราะถ้าไม่มี ก็จะสามารถพิมพ์ค่าออกมาได้  || ทำไงก็ได้ให้เป็น 0  และเอามาแทนค่ตัวต่อไป 
                }
        
                // 1 วนวูปเช็คว่า   (p != 0) หรือไม่   โดย  p มาจาก p = number ที่รับมา 
                // 2 r = (r * 10) + (p%10) ;  
                
                //3   p = p /10 ; เพื่อเช็ค  ว่าให้มันเป็น 0 เพื่อหลุด Loop 
                if (number == r) {
                    // for(int count = 0 ; count <i ;count ++){
                String s1 = String.valueOf(i);     
                
                    //countLines(s1);
                    System.out.println("Number : " + "'"+s1 +"'"+"  is   a palindrome");
        
                    return true; //เรียก return ไป 
                }
                return false;
            }
            
            public static int countLines(String str)
            {
                if (str == null || str.length() == 0)
                    return 0;
                int lines = 1;
                int len = str.length();
                for( int pos = 0; pos < len; pos++) {
                    char c = str.charAt(pos);
                    if( c == '\r' ) {
                        System.out.println("Line 0 : " + "'"+str );
                        
                        lines++;
                        if ( pos+1 < len && str.charAt(pos+1) == '\n' )
                            
                            System.out.println("Line : " + "'"+str );
                            
                          pos++;
                    } else if( c == '\n' ) {
                        lines++;
                        
                        System.out.println("Line 2 : " + "'"+str );
                    }
                }
                return lines;
            }
            
            public static int countLines1(String sd) throws IOException {
                LineNumberReader lineNumberReader = new LineNumberReader(new StringReader(sd));
                int count = 0 ;
                System.out.printf("Line  : " , count = count + 1 );
                lineNumberReader.skip(Long.MAX_VALUE);
                return lineNumberReader.getLineNumber();
            }
        }
        

        【讨论】:

          【解决方案7】:
          public static void main(String args[])
          {
              System.out.print("Enter a number: ");
              Scanner input = new Scanner(System.in);
              int num = input.nextInt();
              int number = num;
              int reversenum = 0;
              while (num != 0)
              {
                  reversenum = reversenum * 10;
                  reversenum = reversenum + num % 10;
                  num = num / 10;
              }
          
              if (number == reversenum)
                  System.out.println("The reverse number is " + reversenum + "\nThen the number is palindrome.");
              else
                  System.out.println("The reverse number is " + reversenum + "\nThen the number is not palindrome.");
          
          }
          

          【讨论】:

            【解决方案8】:

            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)
            

            【讨论】:

              【解决方案9】:

              此代码将 int 转换为 String,然后检查字符串是否为 pallindrome。优点是速度快,缺点是它将 int 转换为 String 从而影响了问题的完美解决方案。

              static int pallindrome=41012;
              static String pallindromer=(Integer.toString(pallindrome));
              static int length=pallindromer.length();
              
              public static void main(String[] args) {
                  pallindrome(0);
                  System.out.println("It's a pallindrome");
              }
              
              static void pallindrome(int index){
                  if(pallindromer.charAt(index)==pallindromer.charAt(length-(index+1))){
                      if(index<length-1){
                          pallindrome(++index);
                      }
                  }
                  else{
                      System.out.println("Not a pallindrome");
                      System.exit(0);
                  }
              }
              

              【讨论】:

                【解决方案10】:

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

                尽管像 Java 这样的语言会在整数溢出时回绕,但这种行为在像 C 这样的语言中是未定义的。(尝试在 Java 中反转 2147483647 (Integer.MAX_VALUE)
                解决方法可能是使用 long 或其他东西,但从风格上讲,我不太喜欢这种方法。

                现在,回文数的概念是数字应该向前和向后读取相同。伟大的。使用此信息,我们可以比较第一个数字和最后一个数字。诀窍是,对于第一个数字,我们需要数字的顺序。比如说,12321。将它除以 10000 将使我们得到前导 1。尾随 1 可以通过将 mod 与 10 一起检索。现在,将其减少到 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;
                }
                

                根据Hardik 的建议进行了编辑,以涵盖数字中有零的情况。

                【讨论】:

                  【解决方案11】:

                  一行python代码:

                  def isPalindrome(number):
                      return True if str(number) == ''.join(reversed(str(number))) else False
                  

                  【讨论】:

                  • 问题[excepts] the algorithm of making the number a string and then reversing the string.
                  【解决方案12】:

                  假设前导零被忽略。以下是一个实现:

                  #include<bits/stdc++.h>
                  using namespace std;
                  vector<int>digits;
                  stack<int>digitsRev;
                  int d,number;
                  bool isPal=1;//initially assuming the number is palindrome
                  int main()
                  {
                      cin>>number;
                      if(number<10)//if it is a single digit number than it is palindrome
                      {
                          cout<<"PALINDROME"<<endl;
                          return 0;
                      }
                      //if the number is greater than or equal to 10
                      while(1)
                      {
                          d=number%10;//taking each digit
                          number=number/10;
                          //vector and stack will pick the digits
                          //in reverse order to each other
                          digits.push_back(d);
                          digitsRev.push(d);
                          if(number==0)break;
                      }
                      int index=0;
                      while(!digitsRev.empty())
                      {
                          //Checking each element of the vector and the stack
                          //to see if there is any inequality.
                          //And which is equivalent to check each digit of the main
                          //number from both sides
                          if(digitsRev.top()!=digits[index++])
                          {
                              cout<<"NOT PALINDROME"<<endl;
                              isPal=0;
                              break;
                          }
                          digitsRev.pop();
                      }
                      //If the digits are equal from both sides than the number is palindrome
                      if(isPal==1)cout<<"PALINDROME"<<endl;
                  }
                  

                  【讨论】:

                  • (否决者请发表评论。)(我不喜欢这是一个仅显示未注释代码的代码答案。)
                  • 嗨@greybeard 现在答案不言自明了吗?
                  • 我认为代码的工作原理在revision 5 中得到了充分的解释。总有改进的余地——你知道Code Review@SE吗?
                  • @greybeard 我以前对这个社区不太了解(在那里有一个帐户,但不是积极参与者,因为我从未仔细注意到该社区的目的)。我浏览了您提供的链接中的内容。听起来很有趣。谢谢。
                  【解决方案13】:

                  在java中检查这个解决方案:

                  private static boolean ispalidrome(long n) {
                          return getrev(n, 0L) == n;
                      }
                  
                      private static long getrev(long n, long initvalue) {
                          if (n <= 0) {
                              return initvalue;
                          }
                          initvalue = (initvalue * 10) + (n % 10);
                          return getrev(n / 10, initvalue);
                      }
                  

                  【讨论】:

                  • 什么语言应该赋予这些(未注释的)陈述意义? isPalindrome(123454328) 会导致算术溢出吗?
                  • (Hrmjah,数到十不像1-2-3那么容易:) 1234554328呢?
                  • 这是一个错误,因为反向数超过了 max int value =2^31-1 ,所以为了得到正确的结果,只需将所有条目转换为 long 并更好地转换为 bigInteger
                  【解决方案14】:

                  只需通过数学函数获取数字的位数,然后使用 '/' 和 '%' 操作进行迭代,如下所示。在 x = (x % 除数) / 10 之后,我们应该将除数除以 100,因为我们进行了 2 次零操作。

                  public static boolean isPalindrome(int x) {
                              if (x < 0) return false;
                              if (x < 10) return true;
                  
                              int numDigits = (int)(Math.log10(x)+1);
                              int divider = (int) (Math.pow(10, numDigits - 1));
                              for (int i = 0; i < numDigits / 2; i++) {
                                  if (x / divider != x % 10)
                                      return false;
                                  x = (x % divider) / 10;
                                  divider /= 100;
                              }
                              return true;
                          }
                  

                  【讨论】:

                    【解决方案15】:

                    我个人是这样做的,没有重叠;无论字符串的长度是偶数还是奇数,代码都会停止在正确的位置检查匹配字符。上面发布的其他一些方法将在不需要时尝试匹配一个额外的时间。

                    如果我们使用 length/2,它仍然可以工作,但它会做一项不需要做的额外检查。例如,“pop”的长度为 3。 3/2 = 1.5,所以它会在 i = 2 时停止检查(因为 1

                    // Checks if our string is palindromic.
                    var ourString = "A Man, /.,.()^&*A Plan, A Canal__-Panama!";
                    isPalin(ourString);
                    
                    function isPalin(string) {
                    // Make all lower case for case insensitivity and replace all spaces, underscores and non-words.
                    string = string.toLowerCase().replace(/\s+/g, "").replace(/\W/g,"").replace(/_/g,"");
                    for(i=0; i<=Math.floor(string.length/2-1); i++) {
                          if(string[i] !== string[string.length-1-i]) {
                            console.log("Your string is not palindromic!");
                            break;
                          } else if(i === Math.floor(string.length/2-1)) {
                            console.log("Your string is palindromic!");
                          }
                        }
                    }
                    

                    https://repl.it/FNVZ/1

                    【讨论】:

                    • 这回答了什么问题?不是How do I check if a number is a palindrome?,其中making the number a string 除外。
                    【解决方案16】:

                    这是我的 Java 代码。基本上比较字符串的第一个和最后一个值以及下一个内部值对等等。

                        /*Palindrome number*/
                        String sNumber = "12321";
                        int l = sNumber.length(); // getting the length of sNumber. In this case its 5
                        boolean flag = true;
                        for (int i = 0; i <= l; ++i) {
                            if (sNumber.charAt(i) != sNumber.charAt((l--) -1)) { //comparing the first and the last values of the string
                                System.out.println(sNumber +" is not a palindrome number");
                                flag = false;
                                break;
                            }
                            //l--; // to reducing the length value by 1 
                        }
                        if (flag) {
                            System.out.println(sNumber +" is a palindrome number");
                        }
                    

                    【讨论】:

                    • 这回答了什么问题?不是How do I check if a number is a palindrome?,其中making the number a string 除外。
                    【解决方案17】:

                    妈的,我疯了! http://www.palindromelist.net/palindromes-d/
                    单步示例:332是回文数吗?

                    n = 332
                    q = n / 10 = 33
                    r = n - 10 * q = 2
                    r > 0
                    r != q
                    n = q = 33
                    n > r
                    q = n / 10 = 3
                    r -= q = 4294967295
                    r *= 10 = 4294967286
                    r += n = 23
                    r != n
                    r != q
                    n = q = 3
                    n > r ? No, so 332 isn't a palindromic number.
                    

                    溢出也不是问题。 两个除法是必要的,在代码 (C#) 中,它们通过乘法完成。 一个 n 位数字:~n/2 个分区!

                    const ulong c0 = 0xcccccccdUL;
                    static bool isPal(uint n)
                    {
                        if (n < 10) return true;
                        uint q = (uint)(c0 * n >> 35);
                        uint r = n - 10 * q;
                        if (r == 0) return false;
                        if (r == q) return true;
                        n = q;
                        while (n > r)
                        {
                            q = (uint)(c0 * n >> 35);
                            r -= q;
                            r *= 10;
                            r += n;
                            if (r == n || r == q) return true;
                            n = q;
                        }
                        return false;
                    }
                    

                    using System;
                    class Program
                    {
                        static void Main()  // take a break
                        {
                            uint n, c; var sw = System.Diagnostics.Stopwatch.StartNew();
                            n = ~0u; c = 0; sw.Restart(); while (n > 0) if (isPal0(n--)) c++;
                            Console.WriteLine(sw.Elapsed + " " + c);                  // 76 s
                            n = ~0u; c = 0; sw.Restart(); while (n > 0) if (isPal1(n--)) c++;
                            Console.WriteLine(sw.Elapsed + " " + c);                  // 42 s
                            n = ~0u; c = 0; sw.Restart(); while (n > 0) if (isPal2(n--)) c++;
                            Console.WriteLine(sw.Elapsed + " " + c);                  // 31 s
                            Console.Read();
                        }
                    
                        static bool isPal0(uint u)
                        {
                            uint n = u, rev = 0;
                            while (n > 0) { uint dig = n % 10; rev = rev * 10 + dig; n /= 10; }
                            return u == rev;
                        }
                    
                        static bool isPal1(uint u)
                        {
                            uint n = u, r = 0;
                            while (n >= 10) r = n + (r - (n /= 10)) * 10;
                            return u == 10 * r + n;
                        }
                    
                        static bool isPal2(uint n)
                        {
                            if (n < 10) return true;
                            uint q = n / 10, r = n - 10 * q;
                            if (r == 0 || r == q) return r > 0;
                            while ((n = q) > r)
                            {
                                q /= 10; r -= q; r *= 10; r += n;
                                if (r == n || r == q) return true;
                            }
                            return false;
                        }
                    }
                    

                    这个似乎更快。

                    using System;
                    class Program
                    {
                        static void Main()
                        {
                            uint n, c; var sw = System.Diagnostics.Stopwatch.StartNew();
                            n = ~0u; c = 0; sw.Restart(); while (n > 0) if (isPal(n--)) c++;
                            Console.WriteLine(sw.Elapsed + " " + c);                 // 21 s
                            Console.Read();
                        }
                    
                        static bool isPal(uint n)
                        {
                            return n < 100 ? n < 10 || n % 11 == 0 :
                                  n < 1000 ? /*          */ n / 100 == n % 10 :
                                 n < 10000 ? n % 11 == 0 && n / 1000 == n % 10 && isP(n) :
                                n < 100000 ? /*          */ n / 10000 == n % 10 && isP(n) :
                               n < 1000000 ? n % 11 == 0 && n / 100000 == n % 10 && isP(n) :
                              n < 10000000 ? /*          */ n / 1000000 == n % 10 && isP(n) :
                             n < 100000000 ? n % 11 == 0 && n / 10000000 == n % 10 && isP(n) :
                            n < 1000000000 ? /*          */ n / 100000000 == n % 10 && isP(n) :
                                             n % 11 == 0 && n / 1000000000 == n % 10 && isP(n);
                        }
                    
                        static bool isP(uint n)
                        {
                            uint q = n / 10, r = n - 10 * q;
                            do { n = q; q /= 10; r -= q; r *= 10; r += n; } while (r < q);
                            return r == q || r == n;
                        }
                    }
                    

                    使用几乎平衡的二叉搜索意大利面条树。

                    using System;
                    class Program
                    {
                        static void Main()
                        {
                            uint n, c; var sw = System.Diagnostics.Stopwatch.StartNew();
                            n = c = 0; sw.Restart(); while (n < ~0u) if (isPal(n++)) c++;
                            Console.WriteLine(sw.Elapsed + " " + c);              // 17 s
                            Console.Read();
                        }
                    
                        static bool isPal(uint n)
                        {
                            return n < 1000000 ? n < 10000 ? n < 1000 ? n < 100 ?
                            n < 10 || n % 11 == 0 : n / 100 == n % 10 :
                            n / 1000 == n % 10 && isP(n) : n < 100000 ?
                            n / 10000 == n % 10 && isP(n) :
                            n / 100000 == n % 10 && isP(n) :
                            n < 100000000 ? n < 10000000 ?
                            n / 1000000 == n % 10 && isP(n) :
                            n % 11 == 0 && n / 10000000 == n % 10 && isP(n) :
                            n < 1000000000 ? n / 100000000 == n % 10 && isP(n) :
                            n % 11 == 0 && n / 1000000000 == n % 10 && isP(n);
                        }
                    
                        static bool isP(uint n)
                        {
                            uint q = n / 10, r = n - 10 * q;
                            do { n = q; q /= 10; r -= q; r *= 10; r += n; } while (r < q);
                            return r == q || r == n;
                        }
                    }
                    

                    不平衡倒置。

                    using System;
                    class Program
                    {
                        static void Main()
                        {
                            uint n, c; var sw = System.Diagnostics.Stopwatch.StartNew();
                            n = c = 0; sw.Restart(); while (n < ~0u) if (isPal(n++)) c++;
                            Console.WriteLine(sw.Elapsed + " " + c);              // 16 s
                            Console.Read();
                        }
                    
                        static bool isPal(uint n)
                        {
                            return
                            n > 999999999 ? n % 11 == 0 && n / 1000000000 == n % 10 && isP(n) :
                            n > 99999999 ? n / 100000000 == n % 10 && isP(n) :
                            n > 9999999 ? n % 11 == 0 && n / 10000000 == n % 10 && isP(n) :
                            n > 999999 ? n / 1000000 == n % 10 && isP(n) :
                            n > 99999 ? n % 11 == 0 && n / 100000 == n % 10 && isP(n) :
                            n > 9999 ? n / 10000 == n % 10 && isP(n) :
                            n > 999 ? n % 11 == 0 && n / 1000 == n % 10 && isP(n) :
                            n > 99 ? n / 100 == n % 10 :
                            n < 10 || n % 11 == 0;
                        }
                    
                        static bool isP(uint n)
                        {
                            uint q = n / 10, r = n - 10 * q;
                            do { n = q; q /= 10; r -= q; r *= 10; r += n; } while (r < q);
                            return r == q || r == n;
                        }
                    }
                    

                    【讨论】:

                    • 您可能需要预先为您的答案提供地图。请将问题的直接答案作为第一个条目。
                    【解决方案18】:

                    下面是快速的答案。 它从左侧和右侧读取数字并比较它们是否相同。 这样做我们将永远不会遇到整数溢出的问题(这可能发生在反转数字方法中),因为我们没有创建另一个数字。

                    步骤:

                    1. 获取数字的长度
                    2. 从长度 + 1(第一个)循环 --> 0
                    3. 获取第 i 个数字并获取最后一个数字
                    4. 如果两个数字不相等,则返回 false,因为数字不是回文
                    5. 我——
                    6. 丢弃 num 的最后一位数字 (num = num / 10)
                    7. 结束返回真

                      func isPalindrom(_ input: Int) -> Bool {
                             if input < 0 {
                                  return false
                              }
                      
                              if input < 10 {
                                  return true
                              }
                      
                              var num = input
                              let length = Int(log10(Float(input))) + 1
                              var i = length
                      
                              while i > 0 && num > 0 {
                      
                                  let ithDigit = (input / Int(pow(10.0, Double(i) - 1.0)) ) % 10
                                  let r = Int(num % 10)
                      
                                  if ithDigit != r {
                                      return false
                                  }
                      
                                  num = num / 10
                                  i -= 1
                              }
                      
                              return true
                          }
                      

                    【讨论】:

                      【解决方案19】:
                      public static boolean isPalindrome(int x) {
                              int newX = x;
                              int newNum = 0;
                              boolean result = false;
                              if (x >= 0) {
                                  while (newX >= 10) {
                                      newNum = newNum+newX % 10;
                                      newNum = newNum * 10;
                                      newX = newX / 10;
                                  }
                                  newNum += newX;
                      
                                  if(newNum==x) {
                                  result = true;
                                  }
                                  else {
                                      result=false;
                                  }
                              }
                      
                              else {
                      
                                  result = false;
                              }
                              return result;
                          }
                      

                      【讨论】:

                        【解决方案20】:

                        这个解决方案非常有效,因为我使用的是 StringBuilder,这意味着 StringBuilder 类被实现为一个可变的字符序列。这意味着您将新的字符串或字符附加到 StringBuilder。

                         public static boolean isPal(String ss){
                           StringBuilder stringBuilder = new StringBuilder(ss);
                           stringBuilder.reverse();
                           return ss.equals(stringBuilder.toString());
                         }
                        

                        【讨论】:

                        • 问题[excepts] the algorithm of making the number a string and then reversing the string.
                        【解决方案21】:
                        public boolean isPalindrome(int x) {
                                if (isNegative(x))
                                    return false;
                        
                                boolean isPalindrome = reverseNumber(x) == x ? true : false;
                                return isPalindrome;
                            }
                        
                            private boolean isNegative(int x) {
                                if (x < 0)
                                    return true;
                                return false;
                            }
                        
                            public int reverseNumber(int x) {
                        
                                int reverseNumber = 0;
                        
                                while (x > 0) {
                                    int remainder = x % 10;
                                    reverseNumber = reverseNumber * 10 + remainder;
                                    x = x / 10;
                                }
                        
                                return reverseNumber;
                            }
                        

                        【讨论】:

                          【解决方案22】:

                          我认为这里提供的最佳解决方案https://stackoverflow.com/a/199203/5704551

                          这个解决方案的编码实现可以是这样的:

                          var palindromCheck(nums) = () => {
                              let str = x.toString()
                              // + before str is quick syntax to cast String To Number.
                              return nums === +str.split("").reverse().join("")  
                          }
                          

                          【讨论】:

                          • 问题[excepts] the algorithm of making the number a string and then reversing the string.
                          猜你喜欢
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 2015-09-15
                          • 1970-01-01
                          相关资源
                          最近更新 更多