Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

home / n The file below is the starter file for the question: import java.util.S

ID: 3813818 • Letter: H

Question

home / n

The file below is the starter file for the question:

import java.util.Scanner;

public class BinToDec {

public static void main(String[] args) {

System.out.println("Please enter the binary representation of an integer: ");

Scanner input = new Scanner(System.in);

String binary = input.next();

int decimal = binToDec(binary);

System.out.printf("The decimal representation is %d ", decimal);

  

input.close();

}

  

public static int binToDec(String binary) {

// Your code here

  

In the file, provide code for the method

public static int binToDec(String binary)

that takes the binary representation of a nonnegative integer as a string and returns the decimal representation of the given integer as an int. You may assume that each character in the input string is 0 or 1.

Run the program to test the correctness of your code for the method. The following are some sample runs:      

Please enter the binary representation of an integer:

The decimal representation is 21

Please enter the binary representation of an integer:

The decimal representation is 2140

Please also provide comments for each line of the program.

must also be written in java C++

Explanation / Answer

HI, Please find my implementation.

import java.util.Scanner;

public class BinToDec {

   public static void main(String[] args) {

       System.out.println("Please enter the binary representation of an integer: ");

       Scanner input = new Scanner(System.in);

       String binary = input.next();

       int decimal = binToDec(binary);

       System.out.printf("The decimal representation is %d ", decimal);

       input.close();

   }

   public static int binToDec(String bin) {

      

       int dec = 0;

      int pow = 1;

      for (int i = (bin.length() - 1); i >= 0; i--) {

      char c = bin.charAt(i);

      dec = dec + (Integer.parseInt(c + "") * pow);

      pow = pow * 2;

      }

      return dec;

   }

}

/*

Sample run:

Please enter the binary representation of an integer:

110

The decimal representation is 6

Please enter the binary representation of an integer:

1111001111

The decimal representation is 975

*/