Converting form Decimal to Binary in Java

Problem:

Write a program that reads a string in binary form from the user (i.e of the form "001010101") and returns the integer equivalent of the string (starting from right to left for the lest significant bit). For example, "0101" is from right to left:
(1* 2^0) + (0* 2^1) + (1* 2^2) + (2* 2^3) which is equal to 5.


Output:

Please enter the binary string:
0001 

The integer value is 1


Solution:

There are two methods to solve this problem. They are listed respectively.
import java.util.Scanner;
public class Problem2version1 
{
 
 public static void main(String[] args)
 {
  Scanner scan=new Scanner(System.in);
  
  System.out.println("Please enter the binary string:");
  String input=scan.next();
  int sum=0;
  int power2=1;
  for(int n=input.length()-1;n>=0;n--)
  {
   if(input.charAt(n)=='1')
    sum += power2;
    
   power2 *= 2;
  }
  System.out.println("The integer value is "+sum);
 }
}

import java.util.Scanner;

public class Problem2
{
 public static void main(String [] args)
 {
  Scanner scan = new Scanner(System.in);
  System.out.println("Please enter the binary string: ");
  String s = scan.next();
  int L = s.length();
  int i = 0;//iterator
      double k = 0;//the value of 1 in the string everytime
  double sum = 0;//the total sum
 
  while (i


3 comments :

  1. It can assist, even so the last buy it's still produced by an individual! The particular binary MULTI LEVEL MARKETING method has become quite popular in the industry along with it's not hard to see why. binary matrix pro

    ReplyDelete
  2. Thanks for sharing this java program. Good explanation.
    https://www.flowerbrackets.com/java-decimal-to-binary-using-tobinarystring-and-stack/

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact