Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Test {
- public static void main(String args[]) {
- Scanner scanner = new Scanner(System.in);
- System.out.println("Enter binary number");
- String input = scanner.next();
- // validate : 0 or 1 only
- for (int pos = 0; pos < input.length(); pos++) {
- char c = input.charAt(pos);
- if (c != '0' && c != '1') {
- System.out.println("Not binary");
- System.exit(1);
- }
- }
- System.out.println("Input valid");
- int result = 0;
- int factor = 1; // place value
- int length = input.length();
- // go through input, starting at the right
- for (int pos = length - 1; pos > -1; pos--) {
- char c = input.charAt(pos);
- if (c == '1') {
- result += factor;
- }
- factor *= 2; // next place value
- }
- System.out.println("In decimal " + result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment