Java回文(布尔法)用迭代解(while循环)
Java Palindrome (Boolean Method) with iterative solution (while loop)
为什么我的回文程序不能正常工作?它总是 returns false
,我说不出为什么。
这是我的代码:
public static boolean isPalindromIterative(String string) {
int a = 0;
int b = string.length() - 1;
while (b > a) {
if (a != b) {
return false;
}
a++;
b--;
}
return true;
}
您正在比较 a 和 b 的值,当您开始比较时它们不相同,因此您的方法得到 false。
在您的 if 条件中,将其更改为 string.charAt(a) != string.chatAt(b)
当你说
while (b > a) {
if (a != b) {
显然a
不等于b
(否则不会进入循环)。根据上下文,我相信您想比较 String
中的字符。我会用 String.toCharArray()
得到一个 char[]
并做类似
的事情
char[] chars = string.toCharArray();
while (b > a) {
if (chars[a] != chars[b]) {
如果代码 while (b > a)
中的 b > a
,则 a
不等于代码 if (a != b)
.
中的 b
要在 java 中检查给定字符串是否为回文,只需使用 StringBuilder
class reverse()
方法并检查给定字符串。
public static boolean isPalindromIterativeStringBuilder(String string) {
StringBuilder sb = new StringBuilder(string);
sb.reverse(); //Reverse to the given string
return sb.toString().equalsIgnoreCase(string); //Check whether given string is equal to reverse string or not
}
这也是一种迭代的方法。
如果我帮助了某人,我会很高兴。 ;)
public static boolean isPalindromeIterative(String string) {
String polindromCheck = string.toUpperCase();
for (int index = 0; index < polindromCheck.length(); index++) {
if (polindromCheck.charAt(index) != polindromCheck.charAt(string.length() - 1 - index)) {
return false;
}
}
return true;
}
为什么我的回文程序不能正常工作?它总是 returns false
,我说不出为什么。
这是我的代码:
public static boolean isPalindromIterative(String string) {
int a = 0;
int b = string.length() - 1;
while (b > a) {
if (a != b) {
return false;
}
a++;
b--;
}
return true;
}
您正在比较 a 和 b 的值,当您开始比较时它们不相同,因此您的方法得到 false。
在您的 if 条件中,将其更改为 string.charAt(a) != string.chatAt(b)
当你说
while (b > a) {
if (a != b) {
显然a
不等于b
(否则不会进入循环)。根据上下文,我相信您想比较 String
中的字符。我会用 String.toCharArray()
得到一个 char[]
并做类似
char[] chars = string.toCharArray();
while (b > a) {
if (chars[a] != chars[b]) {
如果代码 while (b > a)
中的 b > a
,则 a
不等于代码 if (a != b)
.
b
要在 java 中检查给定字符串是否为回文,只需使用 StringBuilder
class reverse()
方法并检查给定字符串。
public static boolean isPalindromIterativeStringBuilder(String string) {
StringBuilder sb = new StringBuilder(string);
sb.reverse(); //Reverse to the given string
return sb.toString().equalsIgnoreCase(string); //Check whether given string is equal to reverse string or not
}
这也是一种迭代的方法。 如果我帮助了某人,我会很高兴。 ;)
public static boolean isPalindromeIterative(String string) {
String polindromCheck = string.toUpperCase();
for (int index = 0; index < polindromCheck.length(); index++) {
if (polindromCheck.charAt(index) != polindromCheck.charAt(string.length() - 1 - index)) {
return false;
}
}
return true;
}