Skip to main content
gamedev.net
🔒 Locked

Binary to Decimal [Java] - Solved!

Started by Tigernado May 1, 2008 at 12:53 PM 3 replies 6.2k views
Original Post
Tigernado
Tigernado
This is part of an assignment that I'm pretty sure is supposed to be simple to implement, but I must have brain freeze or something. This method I wrote will convert the int n to a binary decimal and print it out...backwards(whoops!). I can't use local variables, it must be recursive and the method must have this signature. Is there something I'm doing that's obvious and easy to fix so it will print in the correct order?

	public static void binaryPrint(int n)
	{
	 if(n > 0)
	 {
	 	System.out.print((n % 2 ));
		binaryPrint(n / 2);
	 }
	}
[Edited by - Tigernado on May 1, 2008 1:13:44 PM]
mercurium
mercurium
It looks like you just need to swap the print statement and the recursive call, like this:
public static void binaryPrint(int n){    if(n > 0)    {        binaryPrint(n / 2);        System.out.print((n % 2 ));    }}

Still 2^10 :P
Tigernado
Tigernado
Quote:
Original post by mercurium
It looks like you just need to swap the print statement and the recursive call, like this:
public static void binaryPrint(int n){    if(n > 0)    {        binaryPrint(n / 2);        System.out.print((n % 2 ));    }}


Oh, duh! Thanks!
mercurium
mercurium
Quote:
Original post by Tigernado
Oh, duh! Thanks!


Your welcome [smile]
Still 2^10 :P
Zahlman
Zahlman
When you have a problem with a recursive algorithm, it sometimes helps to think of things functionally rather than procedurally.

Here, we think: "the bit pattern of a number is the bit pattern of half the number (rounded down), followed by the the symbol for the last bit." Then we translate that into the procedure: print the bit pattern for the top of the number first (using the recursive call), then print the last bit.

BTW, you'll want to be more careful about the base case for your recursion. Think about what happens if you try binaryPrint(0), for example.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.