英文:
Palindrome Numbers
问题
以下是翻译好的部分:
我正在编写 Java 代码,其中我必须创建一个带有一个参数并返回布尔值的方法。代码必须判断给定的数字(参数)是否为回文。这是我的代码,但结果始终为 false。有人能否找出问题在哪里?
public class NumberPalindrome {
public static void main(String[] args) {
System.out.println(isPalindrome(121));
}
public static boolean isPalindrome(int number) {
int reverse = 0;
boolean variable = true;
while (number > 0) {
int lastDigit = number % 10;
reverse *= 10;
reverse += lastDigit;
number = number / 10;
}
if (reverse == number) {
variable = true;
} else variable = false;
return variable;
}
}
英文:
I am writing Java code in which I have to create a method that returns boolean with one parameter. The code has to identify in true or false if the number (parameter) provided to it is palindrome or not. This is my code but the outcome is false all the time. Can someone identify what is wrong here?
public class NumberPalindrome {
public static void main(String[] args) {
System.out.println(isPalindrome(121));
}
public static boolean isPalindrome(int number) {
int reverse = 0;
boolean variable = true;
while (number > 0) {
int lastdigit = number % 10;
reverse *= 10;
reverse += lastdigit;
number = number / 10;
}
if (reverse==number) {
variable = true;
} else variable = false;
return variable;
}
}
答案1
得分: 4
你必须将参数中给定的 number
的初始值保留在内存中,以便以后能够与 reverse
进行比较。代码将如下所示。
public class NumberPalindrome {
public static void main(String[] args) {
System.out.println(isPalindrome(121));
}
public static boolean isPalindrome(int number) {
int initialNumber = number;
int reverse = 0;
boolean variable = true;
while (number > 0) {
int lastdigit = number % 10;
reverse *= 10;
reverse += lastdigit;
number = number / 10;
}
if (reverse == initialNumber) {
variable = true;
} else variable = false;
return variable;
}
}
英文:
You must keep in memory the initial value of number
given in parameter to be able to compare it later with reverse
. The code will look like this.
public class NumberPalindrome {
public static void main(String[] args) {
System.out.println(isPalindrome(121));
}
public static boolean isPalindrome(int number) {
int initialNumber = number;
int reverse = 0;
boolean variable = true;
while (number > 0) {
int lastdigit = number % 10;
reverse *= 10;
reverse += lastdigit;
number = number / 10;
}
if (reverse==initialNumber) {
variable = true;
} else variable = false;
return variable;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论