I'm looking to create a simple program that will convert binary numbers to decimal numbers, without using math.pow()
. Here's what I have so far, using Math.pow
at the end:
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {
System.out.println("Enter a binary number");
Scanner inputKeyboard = new Scanner(System.in);
String binaryNumber = inputKeyboard.nextLine();
while (!checkIfBinary(binaryNumber)) {
System.out.println("That is not a binary number. Enter a binary number");
binaryNumber = inputKeyboard.nextLine();
}
int decimalNumber = binaryToNumber(binaryNumber);
System.out.println("Your number in base 10 is " + decimalNumber + ".");
}
public static boolean checkIfBinary(String input) {
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) != '0' && input.charAt(i) != '1') {
return false;
}
}
return true;
}
public static int binaryToNumber(String numberInput) {
int total = 0;
for (int i = 0; i < numberInput.length(); i++) {
if (numberInput.charAt(i) == '1') {
total += (int) Math.pow(2, numberInput.length() - 1 - i);
}
}
return total;
}
}
I'm encountering a problem doing the exponentiation without math.pow
. I know I need to use a loop, and this loop should multiply 2 by itself numberInput.length() - 1 - i
times. But I'm having difficulty implementing this.
I'd work backwards from the end of the string and just calculate the power for each character incrementally:
public static int binaryToNumber (String numberInput) {
int currentPower = 1;
int total = 0;
for (int i = numberInput.length() - 1; i >= 0; i--) {
if (numberInput.charAt(i) == '1') {
total += currentPower;
}
currentPower *= 2;
}
return total;
}