From 78247204fd5f84b84f6b95dc47cf974df69dcfb8 Mon Sep 17 00:00:00 2001 From: wyl <959814898@qq.com> Date: Tue, 25 Jun 2024 15:17:08 +0800 Subject: [PATCH] =?UTF-8?q?leetcode=209.=20=E5=9B=9E=E6=96=87=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/wyl/leetcode/IsPalindrome.java | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 leetcode/src/main/java/com/wyl/leetcode/IsPalindrome.java diff --git a/leetcode/src/main/java/com/wyl/leetcode/IsPalindrome.java b/leetcode/src/main/java/com/wyl/leetcode/IsPalindrome.java new file mode 100644 index 0000000..446a828 --- /dev/null +++ b/leetcode/src/main/java/com/wyl/leetcode/IsPalindrome.java @@ -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 。 + *

+ * 回文数 + * 是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 + *

+ * 例如,121 是回文,而 123 不是。 + *

+ * 示例 1: + *

+ * 输入:x = 121 + * 输出:true + * 示例 2: + *

+ * 输入:x = -121 + * 输出:false + * 解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。 + * 示例 3: + *

+ * 输入:x = 10 + * 输出:false + * 解释:从右向左读, 为 01 。因此它不是一个回文数。 + */ +public class IsPalindrome { + static public boolean isPalindrome(int x) { + if (x < 0) { + return false; + } + Stack stack = new Stack(); + Queue 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)); + } +}