我想將基數10中的數字轉換爲基數2中的數字,但是我遇到了問題。當我運行代碼時,我得到了錯誤順序的基數2。例如,我輸入54並獲得110110而不是011011,這是正確的值。從基數10轉換爲基數2
0
A
回答
1
Java有一個內置的方法來做到這一點:
Integer.toString(int i, int radix);
其中
i
是你的基地至十號,並radix
是你想要它,你的情況的基礎上,2
它將以二進制返回一個字符串。
1
基地10到基地2應反向輸出,我認爲你可以使用array
,然後反向輸出array
public static void main(String arg[]){
int quotient;
int remainder;
List<Integer> arrayList=new ArrayList<Integer>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a decimal number:");
quotient = keyboard.nextInt();
do {
remainder = quotient % 2;
quotient = quotient/2;
// String x = String.valueOf(remainder);
// System.out.print(x);
// System.out.print (remainder);
arrayList.add(remainder);
} while (quotient != 0);
ListIterator<Integer> li;
for (li = arrayList.listIterator(); li.hasNext();) {// 將遊標定位到列表結尾
li.next();
}
for (; li.hasPrevious();) {// 逆序輸出列表中的元素
System.out.print(li.previous() + " ");
}
}
-1
我能解決您的代碼
public class CustomDecimalToBinary {
public static void Dec2Bin() {
int quotient;
int remainder;
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter a decimal number:");
quotient = keyboard.nextInt();
do {
remainder = quotient % 2;
// String x = String.valueOf(remainder);
// System.out.print(x);
System.out.print (remainder);
} while ((quotient /= 2) != 0);
}
}
輸出示例:
Please enter a decimal number:
54
011011
編輯:看來我解決了獲得所需輸出的問題,但你的代碼產生正確的輸出.. 。
+1
54的二進制表示不是011011.這是27的二進制表示形式。54的二進制表示形式是110110.您只是重現了OP的問題。 – EJP
0
嘗試此解決方案,其簡單:
int quotient;
int remainder;
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter a decimal number:");
quotient = keyboard.nextInt();
Stack<Integer> s=new Stack<Integer>();
do {
remainder = quotient % 2;
quotient = quotient/2;
s.add(remainder);
// String x = String.valueOf(remainder);
// System.out.print(x);
//System.out.print (remainder);
} while (quotient != 0);
while(!s.isEmpty()){
System.out.print(s.pop());
}
0
這裏的另一個內置Java函數是
Integer.toBinaryString(int num)
其中num是要轉換
相關問題
- 1. 從基數10轉換爲基數3
- 2. 從基數60轉換爲基數10
- 3. 爲什麼從基數10轉換爲基數2被認爲是慢?
- 4. 將基數10轉換爲基數3數
- 5. 將基數10轉換爲二進制
- 6. 在Java中轉換爲基數10?
- 7. 從基座10轉換到任何基材2和36
- 8. 將密碼子(鹼基64)轉換爲鹼基10數字
- 9. 在JavaCard平臺上將基數10數字轉換爲基數256數字
- 10. 10和2之間的基礎轉換
- 11. 我需要將數字從基數255轉換爲基數256
- 12. Java - 遞歸程序 - 將基數10的數字轉換爲任何基數
- 13. 從基數256轉換爲多基數並返回的算法
- 14. 轉換3.333333333基數爲二
- 15. PEP8 - 基地2至10個基本轉換器
- 16. 將基數爲10的數字轉換爲基數爲N的數字的算法
- 17. 將字符串中的數字轉換爲基數爲10的數字
- 18. 從基本轉換爲Javascript?
- 19. 將基座10轉換爲某個基座
- 20. 我想將基數10的數字改爲基數16
- 21. 將十進制轉換爲基數x
- 22. x86彙編轉換基數
- 23. 使用IEEE 754將浮點數轉換爲基數10使用IEEE 754
- 24. 將八進制和十六進制數字轉換爲基數10
- 25. 將數字轉換爲基於基數的字母數字值36
- 26. 無效字面INT()基數爲10 pypyodbc
- 27. Python ValueError:int()無效的基數爲10
- 28. 問題在view.py:基數爲10
- 29. 無效字面INT()基數爲10
- 30. 數字基數轉換遞歸方法
您可以隨時恢復你所得到的基體10號。 –
你可以把餘數值放到一個堆棧中,並在迭代完成後或者在一個數組中將其打印出來並且顛倒順序 –
你沒有基數10.'nextInt()'傳遞一個二進制整數,基數爲2 。你實際做的是將二進制轉換爲可打印的ASCII。 – EJP