所以我编写了我的Palindrome程序,该程序应该打印范围之间的所有回文数字,但它似乎只打印0到9,这意味着它将所有其他数字评估为false。我不明白为什么?
public class Palindrome
{
public static void main(String [] args)
{
int number = 0;
final int END = 10000;
while (number <= END)
{
if (isPalindrome(number))
{
System.out.print(" " + number);
}
number++;
}
}// end of main method
public static boolean isPalindrome(int number)
{
//local variables
int counter = 0;
int numDigits = 0;
final int END = 10000;
boolean palindrome = false;
while (number <= 10000)
{
//formula for finding the number of digits in a number
numDigits = getNumDigits(number);
//special case if number = 0
if (numDigits == 1)
{
palindrome = true;
break;
}
if(counter < numDigits / 2)
{
if (((number / (int) Math.pow(10, counter)) % 10) != (number / (int) Math.pow(10, numDigits - counter - 1)))
{
palindrome = false;
counter++;
}
else
{
palindrome = true;
}
}
number++;
}// end of loop
return palindrome;
}//end of isPalindrome Method
public static int getNumDigits(int number)
{
//local variables
int numDigits = (int) (Math.log10(number) + 1);
if(number == 0)
{
numDigits = 1;
}
return numDigits;
}//end of getNumDigits method
}
答案 0 :(得分:-1)
我的第一个建议是记录各种方法的输出,以确保您获得正确的输出。使用System.out.println()可以帮助我,因为我看到你无法访问调试器。
另外,你的isPalindrome()函数。我不知道你是否有任何限制,你必须使用数学函数,但你可以在那里做一些事情:
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
android.useDeprecatedNdk=true
这基本上会检查数字的字符串表示形式中的每个字符与字符串末尾的相应字符。您可以将条件除以2,因为在中间点之后您已经检查了字符的相等性。
警告,我可能会有一些错误。我没有测试它。我只是想提出一些想法和一个起点。
祝你好运!