Skip to content

Instantly share code, notes, and snippets.

@odedlaz
Created November 7, 2015 16:50
Show Gist options
  • Save odedlaz/22fe96b55fc26b67944f to your computer and use it in GitHub Desktop.
Save odedlaz/22fe96b55fc26b67944f to your computer and use it in GitHub Desktop.
ToDecimal exercise
public class ToDecimal {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("illegal input");
return;
}
String decimalInBinary = args[0];
if (!decimalInBinary.matches("^(0|1)+$")) {
System.out.println("illegal input");
return;
}
int number = 0;
for (int i = 0, power=decimalInBinary.length()-1; i < decimalInBinary.length() ; i++, power--) {
number += Character.getNumericValue(decimalInBinary.charAt(i)) * Math.pow(2, power);
}
System.out.println(number);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment