Java入門:基礎算法之二進制轉換爲十進制

Java有兩種方法能夠將二進制數轉換爲十進制數:java

1)使用Integer類的Integer.parseInt()方法。spa

2)本身編寫轉換邏輯。code

方法1:使用Integer.parseInt()實現二進制轉換爲十進制blog

import java.util.Scanner;
class BinaryToDecimal {
    public static void main(String args[]){
       Scanner input = new Scanner( System.in );
       System.out.print("Enter a binary number: ");
       String binaryString =input.nextLine();
       System.out.println("Output: "+Integer.parseInt(binaryString,2));
    }
}

輸出:ci

Enter a binary number: 1101
Output: 13

方法2:使用自定義邏輯實現二進制轉換十進制input

public class Details {
 
  public int BinaryToDecimal(int binaryNumber){
 
    int decimal = 0;
    int p = 0;
    while(true){
      if(binaryNumber == 0){
        break;
      } else {
          int temp = binaryNumber%10;
          decimal += temp*Math.pow(2, p);
          binaryNumber = binaryNumber/10;
          p++;
       }
    }
    return decimal;
  }
 
  public static void main(String args[]){
    Details obj = new Details();
    System.out.println("110 --> "+obj.BinaryToDecimal(110));
    System.out.println("1101 --> "+obj.BinaryToDecimal(1101));
    System.out.println("100 --> "+obj.BinaryToDecimal(100));
    System.out.println("110111 --> "+obj.BinaryToDecimal(110111));
  }
}

輸出:class

110 --> 6
1101 --> 13
100 --> 4
110111 --> 55
相關文章
相關標籤/搜索