[英]Remove leading zeros from binary conversion
我想要做的是僅使用按位運算符將用戶輸入的最多 2^32 - 1 的任何數字轉換為其二進制值。 經過多次摸索和修補,我得出了這個結論,這似乎給了我我想要的......幾乎:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = scan.nextLine();
int dec = Integer.parseInt(input);
ArrayList<Integer> binary = new ArrayList<Integer>();
for (int i = 0; i < 32; i++) {
if ((dec & 1) == 0) {
binary.add(0);
} else {
binary.add(1);
}
dec = dec >>> 1;
}
Object[] binaryArray = binary.toArray();
for (int i = binaryArray.length - 1; i >= 0; i--) {
System.out.print(binaryArray[i]);
}
}
這是我現在的問題:這確實輸出了正確的二進制字符串,但我需要刪除前導零,以便十進制數 10 以二進制形式顯示為 1010 而不是 00000000000000000000000000001010。
我是第一學期的 CS 學生,因此將不勝感激任何有關解決問題的幫助或清理代碼的提示。
第三次閱讀您的代碼時,我注意到有些棘手。 你正在做的沒問題,但可能有更好的方法。 我不打算給出答案,但我想看看不同的東西。
不需要代碼中的ArrayList
。 如果你這樣寫代碼怎么辦?
for (int i = 1 << 31; i != 0; i = i >>> 1) {
if ((dec & i) == 0) {
System.out.print( "0" ); //binary.add(0);
} else {
System.out.print( "1" ); //binary.add(1);
}
}
在這里,我只是“邊走邊打印”。 不需要ArrayList
和到數組的轉換。 我已經有一個循環在工作,我不需要添加第二個循環來打印數組的所有值,因為我只是使用我已經擁有的循環。
好的,所以我的第一段代碼是錯誤的。 它以相反的順序打印。 此代碼(應該!未經測試!)開始比特#32,並從那里倒計時,打印位順序。 它還展示了如何在for
循環中使用其他內容,例如i = i >>> 1
而不是總是執行++
。
詳細說明提示:“查看”您的代碼正在做什么的一種快速方法是在您的代碼運行時打印重要值。 例如,要了解您可以使用dec
做什么,請添加一個 print 語句來打印其值。 有些人說使用調試器並逐步執行代碼,但我發現打印語句更快。
for( int i = 0; i < 32 ; i++ ) {
if( (dec & 1) == 0 ) {
binary.add( 0 );
} else {
binary.add( 1 );
}
dec = dec >>> 1;
System.out.println( "DEBUG: " + dec );
}
根據我對您的問題的理解,這是我能想到的。
如果您只想使用自己的方法刪除前導零,這里是解決方法,但是我不建議您這樣做,它體積龐大且不可讀。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = scan.nextLine();
int dec = Integer.parseInt(input);
ArrayList<Integer> binary = new ArrayList<>();
for (int i = 0; i < 32; i++) {
if ((dec & 1) == 0) {
binary.add(0);
} else {
binary.add(1);
}
dec = dec >>> 1;
}
StringBuilder ss = new StringBuilder();
for (int i = binary.size() - 1; i >= 0; i--) {
ss.append(binary.get(i));
}
System.out.println(Integer.parseInt(ss.toString()));
}
或者您可以使用這種方法較少的代碼:) 易於閱讀
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = scan.nextLine();
int dec = Integer.parseInt(input);
char[] arr = Integer.toBinaryString(dec).toCharArray();
StringBuilder sb = new StringBuilder();
for (Character c : arr) {
sb.append(c);
}
System.out.println(sb);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.