import java.util.Scanner; public class Bin2Dec { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter a binary number: "); int n1 = in.nextInt(); int n2 = n1; in.close(); int value1 = 0; int count = 0; while (n1 != 0) { int lastDigit = n1 % 2; value1 += lastDigit * Math.pow(2, count); n1 /= 10; ++count; } System.out.println(value1); // Alternative approach: instead of using Math.pow(), use a weight // variable that doubles after each iteration int value2 = 0; int weight = 1; while (n2 != 0) { int lastDigit = n2 % 2; value2 += lastDigit * weight; n2 /= 10; weight *= 2; } System.out.println(value2); } }