Given a binary number ,help Von Neuman to find out its decimal representation. For eg 000111 in binary is 7 in decimal.
NOT ABLE TO SOLVE
Von neuman loves binary problem
Hi
What problem are you facing in this question? Is your program not running correctly or you have problem understanding the logic?
The question simply says that you will be given a number in binary form and you need to convert it in decimal form.
Hi
As you are not responding to this thread, I am marking your doubt as Resolved for now. Re-open it if required.
Please mark your doubts as resolved in your course’s “ Ask Doubt ” section, when your doubt is resolved.
I am not able to frame the logic
srry i didnt knew that i need to come in the discussion forum thats why couldnt reply early.
Hi
The logic for the question is:
For binary number 110010 , Decimal number = 1.2^5 + 1.2^4 + 0.2^3 + ……+ 0.2^0.
- The idea is to extract the digits of given binary number starting from right most digit and keep a variable dec_value.
- At the time of extracting digits from the binary number, multiply the digit with the proper base (Power of 2) and add it to the variable dec_value.
- In the end, the variable dec_value will store the required decimal number.
Hope it helps.
yaa that i know but my doubt is that user can enter 0-9 any number how to ensure it accepts only 0 and 1. Do i need to apply if-else loop
?
Assume that there are numbers only with digits 0 and 1 and write your code. There are no test cases at the backend with digits other than 0 and 1.
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scn =new Scanner(System.in);
int number=scn.nextInt();
for(int i=1;i<=number;i++)
{
Scanner scan =new Scanner(System.in);
int n=scan.nextInt();
int x=0;
int y=0;
int val=1;
//
while(n/10!=0||n%10!=0)
{
x=n%10;
n=n/10;
y=y+x*val;
val=val*2;
}
System.out.println(y);
}
}
}
This is my code
im getting error like this
Exception in thread “main” java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Main.main(Main.java:7)
How to slove this?