Issue
I want to make a java code that converts any decimal number inputted, into binary number. Although the array method is easy, it doesn't actually prints a number(it prints array), nor does it seem to correctly use the algorithm we use manually. So I'm trying to do it without array. The problem is it sometimes giving correct answers, and sometimes giving wrong answers. I think the problem might be in multiplying by zero in the last cycle of loop, but I'm not sure. The code I wrote as comment was a failed try to resolve the issue.
import java.util.Scanner;
public class DecToBin {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long dec = 0, num = 0, rem = 0;
System.out.print("Enter A Decimal Number: ");
dec = sc.nextLong();
while(dec > 0){
rem = dec % 2;
num += rem;
num *= 10;
dec /= 2;
}
// if(num % 100 == 10){
// num = num/10;
// }
System.out.println("Binary Equivalent: " + num);
}
}
Solution
I found following "direct" issues with your code:
- You are not reversing the final number. In the manual way of converting DEC->BIN, we reverse the final representation. Hint: Dry run for input 11
- You are doing
num += rem; num *= 10
. The order is wrong. You should be multiplying it before you add the remainder. eg. Your code will output1010
for5
, instead of101
. - By your method, you are trying to represent decimal number into its binary representation as
int
, which limits your input to2047
, as2048
and above need 11+ digits for their binary representation and you can't have that inint
. You should useString
if you don't want to use array. Also, reversing would be easier.
something like:
import java.util.Scanner;
public class DecToBin {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int dec = 0, num = 0;
System.out.print("Enter A Decimal Number: ");
dec = sc.nextInt();
String bi = "";
while(dec > 0){
int rem = dec % 2;
// num *= 10;
// num += rem;
bi += Character.toString(rem + 48);
dec /= 2;
}
// if(num % 100 == 10){
// num = num/10;
// }
System.out.println("Binary Equivalent: " + new StringBuilder(bi).reverse().toString());
}
}
Answered By - vish4071
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.