我正在尝试使用Java解决this problem。 (您只需要真正查看public static int[] findBase at the end)

import java.io.*;
import java.math.*;
public class palsquare {

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    BufferedReader br = new BufferedReader(new FileReader("palsquare.in"));
    int base = Integer.parseInt(br.readLine());
    br.close();
    PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("palsquare.out")));
    for(int x = 1; x < 300; x++){
        boolean dat = true;
        int[] square = findBase(base, x * x);
        System.out.println("Finished, here is the result: ");
        for(int m = 0; m < square.length; m++){
            System.out.print(square[m] + " ");
        }
        System.out.print("\n\r");
        for(int j = 0; j < square.length/2; j++){
            if(square[j] != square[square.length - 1 - j]){
                dat = false;
            }
        }
        if(dat){
            System.out.println("///////");
            int[] wow = findBase(base, x);
            for(int j = 0; j < wow.length; j++){
                pw.print(wow[j]);
            }
            pw.print(" ");
            for(int j = 0; j < square.length; j++){
                pw.print(square[j]);
            }
            pw.print("\n");
        }
    }
    pw.close();
}

public static int[] findBase(int Base, int num){
    System.out.println("Handling " + num);
    int index = 0;
    while(Math.pow(Base, index) <= num){
        index++;
    }
    System.out.println("The number of digits: " + index);
    if(index < 1){
        index = 1;
    }
    int remaining = num;
    int[] thisOne = new int[index];
    for(int i = index - 1; i <= 0; i++){
        int thisDigit = 0;
        while(Math.pow(Base, i) * thisDigit < remaining){
            thisDigit++;
        }
        thisOne[i] = thisDigit;
        System.out.println("The current digit: " + thisDigit);
        remaining = remaining - (int) Math.pow(Base, i) * thisDigit;
        System.out.println("The amount remaining: " + remaining);
    }
    return thisOne;
}

}


我的代码。

当我运行带有大于Base的值的findBase时,findBase返回正确大小的数组,但是它用零填充。我试图弄清楚为什么会这样,而最后两个System.out.println都没有运行。我也猜想与更新机制相同。有谁知道我的程序为什么在这么多的代码上“跳过”?

最佳答案

 for(int i = index - 1; i <= 0; i++)


这应该改为:

  for(int i = index - 1; i >= 0; i--){


由于索引在上下文中似乎是一个正整数

07-28 13:53