我必须编写一个程序在java(家庭作业),给出输入(x),在二进制输入,告诉如果输入是回文,并告诉如果从输入二进制是一个回文。我可能不会使用除System.out.print之外的其他api,并且我可能不会使用字符串。Java十进制到二进制没有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");
}
}
}
我试图使用长而不是int的v和w,但后来我得到一个错误,返回值必须是int。 – Waarten
你想在启动程序时指定一个数字吗? – hellectronic
@hellectronic不,int x = ...;部分就够了。 – Waarten