Please explain if the following code is actually correct. If the following code
ID: 3781131 • Letter: P
Question
Please explain if the following code is actually correct. If the following code correct, please explain why the code works and is also correct. Don’t use * Java’s Integer .toBinaryString(int) in this program./* According to the textbook and the instructor, I am not supposed to use arrays such as int binary[] = new int[25]; I guess this is the reason why this problem is starting to look kind of hard. Chapter 5 Exercise 37: Java Programming
*
* (Decimal to binary) Write a program that prompts the user to enter a
* decimal integer and displays its corresponding binary value. Don’t use
* Java’s Integer .toBinaryString(int) in this program./* Note : if access specifier is specified as public then file name and class name should be same and main should be within that class only */
Programming Exercise Solution
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Dec_to_bin
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
//Take User input from keyboard
System.out.println("Enter decimal number: ");
int num = in.nextInt();
int bin =0;
int i=0;
while (num != 0)
{
int d = num % 2;
bin=bin+(d*((int)Math.pow(10,i)));
num /= 2;
i++;
}
System.out.print(" Binary representation is:");
System.out.print(bin);
System.out.println();
}
}
Explanation / Answer
Following code is correct.
You just need to add "import java.util.Scanner;" before class as it is requried for using scanner.
Reason for correctness.
>> int d = num % 2;
it is checking whether bit in binary represenation will be set or not.
>> bin=bin+(d*((int)Math.pow(10,i)));
This is shifting set bit to its correct position in binary representation and then add existing binary representation of number so far.
>> num /= 2
This will reduce number to half (that is shift last bit to go away) and thus helpng in using one bit at a time.
As you are using int in this you won't be able to handle large values depending on large values of decimal
It will work till 1023
For 1024 it will print 2147483647 because of limit on max value of int.