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
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
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
ReplyDeleteNice article about Java Conversion Decimal to Binary .
ReplyDeletethanks
Thanks for sharing this java program. Good explanation.
ReplyDeletehttps://www.flowerbrackets.com/java-decimal-to-binary-using-tobinarystring-and-stack/