簡體   English   中英

使用老式的方法將整數轉換為二進制

[英]Converting an integer to binary using old-school way

我知道使用System.out.println(Integer.toBinaryString(num));在Java中實現此目標非常容易System.out.println(Integer.toBinaryString(num));

但是,我想使用循環執行此操作,我嘗試了此操作,但順序相反。 我怎樣才能解決這個問題:

public class Main {

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    int num = in.nextInt();

    while (num >= 2) {

      System.out.print(num % 2);

      num = (int) num / 2;
    }

    System.out.println(num);
  }
}

例如;

輸入num = 8

打印0001但必須改為1000

使用字符串存儲結果:

String binaryString = Integer.toString(num % 2);
while (num >= 2) {
    num = (int) num / 2;
    binaryString = Integer.toString(num % 2) + binaryString;
}
System.out.println(binaryString);

正如Brian所建議的,將中間值存儲在String中。

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        String x = "";

        while (num >= 2) {
            x = x + Integer.valueOf(num % 2);

            num = (int) num / 2;
        }

        String newX = new StringBuilder(x).reverse().toString();

        System.out.print(num + newX);
    }
}

如果你真的想OLD- 學校 ,那么你可以遞歸地做到這一點:

public static void main(String[] args) {
    try (Scanner in = new Scanner(System.in)) {
        int num = in.nextInt();
        System.out.println(getBinaryString(num));
    }
}

//Does not take care of negative values
private static String getBinaryString(int num) {
    if (num <= 2) {
        return "" + (num % 2);
    }
    return getBinaryString(num / 2) + (num % 2);
}

下面的代碼並不能太當真,它是一種非常古老的實現,它利用了傳統的位掩碼和位移位。 它也適用於負數,因此產生的結果與Integer.toBinaryString()相同。 通過使中間char數組成為靜態線程安全來換取性能,因此請確保不要在多線程環境中使用它。 當然,我們將在不同的地方使用相同的常量值,無意義的標識符和其他 混淆 優化方法,以確保 lamers不會立即了解正在發生的事情, 初學者會看到好的代碼應該是什么樣子。 切記:較短的代碼=更好的代碼,較小的文件=更少的傳輸時間,因此請盡可能省略無用的空格和換行符。 每行不超過80個字符,這樣您的矩陣打印機將很高興將您的代碼打印在清單紙上,而不會帶來任何麻煩。

private static char[]a=new char[32];
public static String b(int c) {
    int d=32; do a[--d]=(char)(48+(c&1)); while ((c>>>=1)!=0);
    return new String(a,d,32-d);
}

結論:很高興有Integer.toBinaryString()類的東西可以在生產代碼中使用。

您可以提前計算位數,然后反向打印位數。

這將適用於任何給定的基數(2-9)。

import java.util.Scanner;

public class Main {
    public static final int BASE = 2;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: "); // Promp user

        int num = in.nextInt();
        int bits = (int) Math.floor(Math.log(num) / Math.log(BASE)); // Calculate min bits

        for (int bit = bits; bit >= 1; bit--) { // Loop in reverse
            int factor = (int) Math.pow(BASE, bit);
            System.out.print(num / factor);
            num = (int) num % factor;
        }

        System.out.println(num);
        in.close();
    }
}

支持任何基礎/字母。

import java.util.Scanner;

public class Main {
    public static final int BASE = 16;
    public static final char[] ALPHABET = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
        'U', 'V', 'W', 'X', 'Y', 'Z'
    };

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: ");

        int num = in.nextInt();
        int bits = (int) Math.floor(Math.log(num) / Math.log(BASE)) + 1;

        if (bits <= 0) {
            System.out.println(0);
        }

        for (int bit = bits - 1; bit >= 0; bit--) {
            int factor = (int) Math.pow(BASE, bit);
            System.out.print(ALPHABET[num / factor]);
            num = (int) num % factor;
        }

        in.close();
    }
}

這是Viktor建議的具有自定義基礎支持的遞歸實現。

import java.util.Scanner;

public class Main {
    public static final int BASE = 16;
    public static final char[] ALPHABET = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
        'U', 'V', 'W', 'X', 'Y', 'Z'
    };

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: "); // Prompt user
        System.out.println(integerToString(in.nextInt()));
        in.close();
    }

    public static String integerToString(int n) {
        return integerToString(n, BASE);
    }

    public static String integerToString(int n, int radix) {
        return integerToString(n, radix, ALPHABET);
    }

    public static String integerToString(int n, int radix, char[] alphabet) {
        return (n > radix ? integerToString(n / radix, radix, alphabet) : "") + ALPHABET[n % radix];
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM