![](/img/trans.png)
[英](java) convert a decimal number to binary without using parseint
[英]Convert Decimal Number to Binary without using Array
我想制作一個 java 代碼,將輸入的任何十進制數轉換為二進制數。 雖然數組方法很簡單,但它實際上並沒有打印一個數字(它打印的是數組),它似乎也沒有正確使用我們手動使用的算法。 所以我試圖在沒有數組的情況下做到這一點。 問題是它有時給出正確答案,有時給出錯誤答案。 我認為問題可能出在循環的最后一個周期中乘以零,但我不確定。 我作為評論寫的代碼是解決問題的失敗嘗試。
import java.util.Scanner;
public class DecToBin {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long dec = 0, num = 0, rem = 0;
System.out.print("Enter A Decimal Number: ");
dec = sc.nextLong();
while(dec > 0){
rem = dec % 2;
num += rem;
num *= 10;
dec /= 2;
}
// if(num % 100 == 10){
// num = num/10;
// }
System.out.println("Binary Equivalent: " + num);
}
}
這是我第一次回答,所以如果有任何問題請告訴我:-)
您可以嘗試使用 String 作為中間體。 簡短而簡單......但我不知道這是否算作一個數組:-)
您的 while-part 將是這樣的:
String strBin = "";
while(dec > 0){
strBin = String.valueOf(dec%2) + strBin;
dec /= 2;
}
num = Long.valueOf(strBin);
通過在前一個 String 前面添加,二進制數中的位順序是正確的,因此從右到左構建結果。
另外,我不會使用 Long(最后一行......數字),因為它限制了你的最大結果。 但如果你必須......嗯
這個問題適用於遞歸解決方案
private static int DecToBin(final int input, final int result) {
if (input == 0) {
return result;
}
return DecToBin(input / 2, result * 10 + input % 2);
}
我發現您的代碼存在以下“直接”問題:
num += rem; num *= 10
num += rem; num *= 10
。 順序錯了。 在添加余數之前,您應該先乘以它。 例如。 您的代碼將 output 1010
用於5
,而不是101
。int
,這將您的輸入限制為2047
,因為2048
及以上需要 11+ 位的二進制表示,而您不能在int
中使用它。 如果不想使用數組,則應使用String
。 另外,倒車會更容易。就像是:
import java.util.Scanner;
public class DecToBin {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int dec = 0, num = 0;
System.out.print("Enter A Decimal Number: ");
dec = sc.nextInt();
String bi = "";
while(dec > 0){
int rem = dec % 2;
// num *= 10;
// num += rem;
bi += Character.toString(rem + 48);
dec /= 2;
}
// if(num % 100 == 10){
// num = num/10;
// }
System.out.println("Binary Equivalent: " + new StringBuilder(bi).reverse().toString());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.