• 9. Palindrome Number


    思路1:利用Reverse Integer的方法,求的转换后的数字,然后比较是否相等。

    思路2:从两头依次取数字比较,向中间推进。

     1     // Revert Integer解法,把反转后的和原数据对比,相同返回true
     2     public static boolean isPalindrome(int x) {
     3         int real = x;
     4         if (x < 0) {
     5             return false;
     6         }
     7         long sum = 0;
     8         while (x > 0) {
     9             int temp = x % 10;
    10             sum = sum * 10 + temp;
    11             if (sum > Integer.MAX_VALUE) {
    12                 return false;
    13             }
    14             x = x / 10;
    15         }
    16         if (sum == real) {
    17             return true;
    18         } else {
    19             return false;
    20         }
    21     }
    22 
    23     // left和right比较,例如1234321:左一和右一比较,左二和右二比较,如果全部相等返回true
    24     public static boolean isPalindrome_2(int x) {
    25         if (x < 0) {
    26             return false;
    27         }
    28         int len = 1;
    29         while (x / len >= 10) {
    30             len = len * 10;
    31         }
    32         while (x > 0) {
    33             int left = x / len;
    34             int right = x % 10;
    35             if (left != right) {
    36                 return false;
    37             }
    38             x = (x - left * len) / 10;
    39             len = len / 100;
    40         }
    41         return true;
    42     }
  • 相关阅读:
    java.sql.SQLSyntaxErrorException: ORA-01722: 无效数字
    Lambda表达式详解
    MAC JDK 卸载方法(彻底卸载)
    JAVA final关键字
    JAVA访问权限
    JAVA重写
    JAVA继承
    单例设计模式---懒汉式和饿汉式
    JAVA构造块和静态代码块
    Java static关键字
  • 原文地址:https://www.cnblogs.com/imyanzu/p/5157738.html
Copyright © 2020-2023  润新知