Binary to Decimal and Decimal to Binary in Java | AskTheCode

Java program for user driven Binary to Decimal and Decimal to Binary conversion | Java Solutions

Problem:

Write a Java method that accepts a binary number and converts it to decimal, then display the result.

Sample output:

Enter the binary number:

110

6

Press 1 perform Decimal to Binary conversion:

1

Enter the decimal number:

14

1110

Code:

import java.lang.*;
import java.io.*;

class Binary_To_Decimal{
	public static void main (String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Enter the binary number: ");
		String n = br.readLine();
		System.out.println(Integer.parseInt(n, 2));
		System.out.println("Press 1 perform Decimal to Binary conversion: ");
		int choice = Integer.parseInt(br.readLine());
		if (choice == 1){
			System.out.println("Enter the decimal number: ");
			int num = Integer.parseInt(br.readLine());
			System.out.println(Integer.toBinaryString(num));
		}
	}
}
20 views0 comments

Recent Posts

See All

Golf CodeChef Solution in Java - AskTheCode

CodeChef May Long Challenge Solution | Golf (LKDNGOLF) solution | AskTheCode Golf (LKDNGOLF) solution Problem: It's a lockdown. You’re bored in your house and are playing golf in the hallway. The hall

Solubility - CodeChef Solution in Java and C++| AskTheCode

CodeChef May Long Challenge Solution | Solubility (SOLBLTY) solution | AskTheCode Solubility (SOLBLTY) solution Problem: Suppose for a unit rise in temperature, the solubility of sugar in water increa

Valid Paths CodeChef Solution in C++ | AskTheCode

CodeChef May Long Challenge Solution | Valid Paths (VPATH) solution | AskTheCode Valid Paths (VPATH) CodeChef solution Problem: You are given a tree with N nodes numbered from 1 to N. A set S of nodes