leetcode 9. 回文数

This commit is contained in:
wyl
2024-06-25 15:17:08 +08:00
parent 48c031f9a5
commit 78247204fd
@@ -0,0 +1,66 @@
package com.wyl.leetcode;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
/**
* 9.给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
* <p>
* 回文数
* 是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
* <p>
* 例如,121 是回文,而 123 不是。
* <p>
* 示例 1
* <p>
* 输入:x = 121
* 输出:true
* 示例 2
* <p>
* 输入:x = -121
* 输出:false
* 解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
* 示例 3
* <p>
* 输入:x = 10
* 输出:false
* 解释:从右向左读, 为 01 。因此它不是一个回文数。
*/
public class IsPalindrome {
static public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
Stack<Integer> stack = new Stack();
Queue<Integer> queue = new LinkedList();
do {
stack.push(x % 10);
queue.add(x % 10);
x = x / 10;
} while (x != 0);
while (!stack.empty()) {
if (!queue.poll().equals(stack.pop())) {
return false;
}
}
return true;
}
static public boolean isPalindrome1(int x) {
if (x < 0) {
return false;
}
int metadata = x;
int res = 0;
do {
res = 10 * res + (x % 10);
x = x / 10;
} while (x != 0);
return metadata == res;
}
public static void main(String[] args) {
System.out.println(isPalindrome1(0));
}
}