I\'m trying to make a code that converts number into binary number. But my outpu
ID: 3543256 • Letter: I
Question
I'm trying to make a code that converts number into binary number. But my output of remainder (number%2) seems not working properly. For example, 1%2 should be 1 but it prints out that it is 0) Can anybody tell me what the problem is?
import java.util.Scanner;
public class BinaryRep {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a number");
int number = input.nextInt();
int newnum = 0;
while (number != 0 ) {
number /= 2;
int remainder = number % 2;
newnum = newnum * 10 + remainder;
System.out.println(remainder);
System.out.println(newnum);
}
}
}
Explanation / Answer
Declare your "int remainder;" outside the while loop, in c I might have got an error in "int remainder = number % 2:" statement, I've less idea about java, so may be it will work in java..
Anyways, I'll correct your algorithm, editting is needed in your while loop:
while(number!=0) {
int remainder = number % 2;
number /= 2;
newnum = newnum * 10 + remainder;
System.out.println(remainder);
}
System.out.println(newnum);
Explaination:
if your number is 1, in your algorithm, first it'll divide it by 2, means it becomes 0, thus the output comes 0.
Your algorithm would have always missed the most significant bit. This means your algo will work fine for even numbers but not for odd numbers.
But this is not the case with my algorithm.
I hope that this works.