I have a homework to do a decimal to binary conversation. This is the code I have:
int num = 0;
int temp = 0;
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
//System.out.print(""+ num%2+ (num%2)%2);
while(num != 0) {
temp = num;
System.out.print(""+(int) temp % 2);
num = num / 2;
}
It is working fine, but it giving me the output as LSB and not as MSB.
For example:
35
110001
but I need it to be 100011.
I cannot use any function or method to reverse it. I know I can put it in an array, string or whatever and do some magic. But I can use only the while loop, modulo and print.
Any Suggestions?
Don’t output each digit as you find them. Build your output incrementally and then print it at the end.
You may need to modify this to handle large or negative numbers.