Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121 Output: trueExample 2:
Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.Example 3:
Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome.Follow up:
Coud you solve it without converting the integer to a string?
判判断一个数是否为回文数,并且不可以使用额外存储空间
使用字符串来实现,代码比较简洁,也很好理解,源码如下:
/** * 直接使用字符串的方式 * @param x * @return */ public static boolean isPalindrome_2(int x) { String b = String.valueOf(x); StringBuilder before = new StringBuilder(b); String after = before.reverse().toString(); return b.equals(after); }使用官网提供的解题思路,逐次去判断给定数字的最高位和最低位是否相等来决定是否为回文数字
①创建两个int变量left和right;
②left表示当前数x的最高位数字,right表示当前数x的最低位数字;
③若 left == right,则将当前数x去掉最高位和最低位,并且继续执行②,直至 x == 0;
public static boolean isPalindrome(int x) { int length = 1; // 负数 越界肯定不是回文 if (x < 0 || x > Integer.MAX_VALUE) { return false; } while(x / length >= 10) { length *= 10; } while (x != 0) { // x 的最高位 int left = x / length; // x 的最低位 int right = x % 10; // 有不相等的 if (left != right) { return false; } // 去掉已经比较过得最高位和最低位 如 12345 变成 234 x = (x % length) / 10; // 去除最高位和最低位之后 x 的长度也相应要减少 length /= 100; } return true; }Github地址:https://github.com/Bylant/LeetCode
地址:https://blog.csdn.net/ZBylant 微信公众号