我必须用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");
}
}
}