-1

我必须用java(家庭作业)编写一个程序,给出输入(x),二进制输入,告诉输入是否是回文,并告诉输入的二进制是否是回文。我可能不会使用 System.out.print 以外的 api,也可能不会使用字符串。

到目前为止一切顺利:我已经编写了程序,它一直工作到 x = 1023(因为 int)。我必须编辑哪段代码,所以输入可以是任何正数?

class Palindromes {
public static int DtoBinary(int x) {
    int y = x;
    int w = 1;
    int v = 0;
    int z = 1;
    int u = 0;
    while (z < y) {
        z = z * 2;
        u++;
    }
    z = z / 2;
    for (int t=1; t<u; t++) {
        w = 10 * w;
    }
    v = v + w;
    y = y - z;
    while (y > 0) {
        z = z / 2;
        if (z <= y) {
            w = w / 10;
            v = v + w;
            y = y - z;
        } else if (y == 1) {
            v = v + 1;
            y = 0;
        } else {
            w = w / 10;
            v = v + 0;
        }
    }
    return v;
}

public static boolean Palindrome(int x) {
    int s = x;
    int r = 0;
    while (s > 0) {
        int q = s % 10;
        r = r * 10 + q;
        s = s / 10;
    }
    if (x == r) {
        return true;
    } else {
        return false;
    }
}

public static void main(String[] args) {
    int x = 1023;

    System.out.print(x + " " + DtoBinary(x));
    if (Palindrome(x)) {
        System.out.print(" yes");
    } else {
        System.out.print(" no");
    }
    if (Palindrome(DtoBinary(x))) {
        System.out.print(" yes");
    } else {
        System.out.print(" no");
    }
}
}
4

2 回答 2

0

您可以使用 char 数组而不是 int 来存储回文类的大二进制数。

public static char[] DtoBinary(int x) {
  <insert code to convert x to an array of zeroes and ones>
}

您将需要编写一个方法来检查 char 数组是否是回文。

于 2011-11-22T16:06:46.743 回答
-1

我可以为家庭作业提供简短的解决方案。

public static boolean isPalindrome(int x) {
     String inputted = "" + x; 
     String reverse = new StringBuffer(inputted).reverse().toString();    

     return inputted.equals(reverse);
}

或者

public static boolean isPalindrome(int x) {
     String inputted = "" + x;
     int length = inputted.length; 
     for(int i = 0; i< inputted/2; i++){
        if(inputted.charAt(i)!= inputted.charAt(inputted - 1 - i)){
           return false;
        }
     }

     return true;
}
于 2011-11-22T12:05:26.373 回答