高分悬赏:Java语言怎么判断一个数字是不是回文数,或者叫做对称数,具体的代码
问题描述:
高分悬赏:Java语言怎么判断一个数字是不是回文数,或者叫做对称数,具体的代码
答
有一个简单的方法:用 StringBuffer 的 reverse 得到反转后的字符串,然后再用 equals 为真就是回文了哦。
答
public class Hws {
public static void main(String[] args) {
int num = 123321;
System.out.println(hws(num));
}
public static boolean hws(int a) {
if (a < 0) {
return false;
}
String str = String.valueOf(a);
char[] chars = str.toCharArray();
int len = chars.length;
for (int i = 0; i < len; i++) {
if (chars[i] != chars[len - i - 1]) {
return false;
}
}
return true;
}
}
答
public class Test6 {
public static void main(String[] args) {
System.out.println(hws(123321));
}
public static boolean hws(int a) {
if (a < 0) {
return false;
}
String str = String.valueOf(a);
char[] chars = str.toCharArray();
int len = chars.length;
if (len % 2 != 0) {
return false;
}
for (int i = 0; i < len; i++) {
if (chars[i] != chars[len - i - 1]) {
return false;
}
}
return true;
}
}
答
回文串一定想到的是中心扩展法,选取mid中间值后,对比其左右边数字是否相同,左右值通过除对应的位数再用10取余得到(例如1234中左边2第二位,对应是百位数,所以通过(1234/100)%10最终的到2,其右边3也可以通过(1234/10)%10得到)。
我之前写的python算法,如果会语法可以参考一下:
""""
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
elif x >= 0 and x < 10:
return True
# 中心扩展
temp_x = x
x_len = 1
while temp_x > 9:
x_len = x_len + 1
temp_x = temp_x // 10
mid = int(10 ** (x_len // 2))
L, R = mid, mid
# 偶数情况
if x_len % 2 == 0:
L, R = mid, mid // 10
while L <= x and R > 0:
left_mod = (x // L) % 10
right_mod = x % 10 if R == 1 else (x // R) % 10
if left_mod == right_mod:
L = L * 10
R = R // 10
else:
return False
return True
""""
还可以去leetcode:https://leetcode-cn.com/problems/palindrome-number/中寻找相关解题贴。
授人予鱼不如授人以渔,望受用。