我必須編寫一個程序在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