Please explain if the following code is actually correct If
Please explain if the following code is actually correct. If the following code correct, please explain why the code works and is also correct.
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();
}
}
Solution
The problem in your code lies here -
bin=bin+(d*((int)Math.pow(10,i)));
Working Code is as below:
public class DecimalToBinary {
public void convertToBinary(int number){
int binary[] = new int[25];
int index = 0;
while(number > 0){
binary[index++] = number%2;
number = number/2;
}
for(int i = index-1;i >= 0;i--){
System.out.print(binary[i]);
}
}
public static void main(String a[]){
DecimalToBinary db = new DecimalToBinary();
db.convertToBinary(25);
}
}
OUTPUT:
11001

