Lil java help for a noob please

Soldato
Joined
20 Jun 2005
Posts
3,826
Location
London..
Hey everyone.

I'm trying to write a program which converts decimal into binary using recursion and vice versa.

So far i have been able to write the method for decimal to binary and it compiles fine and runs ok, apart from the fact that it displays the binary answer backwards.

Here is my code:

Code:
public static String decTobin (int n){
	if (n==0){
		return "0";
	}
	if (n%2==0){
		return "0" + decTobin(n/2);
	}
	else {
		return "1" + decTobin(n/2);
		}
 
 
}

For example, if i put in 5 to convert to binary, instead of getting 0101 as the answer i get 1010.

How can i reverse the output? I have been trying so hard...

Thanks
 
Well think about it, run through on a piece of paper what happens if n = 5.

PS: Your answer isn't backwards - think of 5 as 101, not 0101.

Another thing, the only way for your method to exit is if n==0 which then results in 0 always being the last digit (on the right hand side) - does every binary number in the world have a 0 as the furthest digit on the RHS?
 
Last edited:
Thank you very much for the reply..

I ran through it on a piece of paper with 5, and i get 1010 as well? which is reads left to right to make 5 instead of right to left like it should when reading binary.

Am i doing something wrong? :(
 
change it to return dectobin(n/2) + "1"?
Another thing, the only way for your method to exit is if n==0 which then results in 0 always being the last digit (on the right hand side) - does every binary number in the world have a 0 as the furthest digit on the RHS?
edit, gotcha
 
Last edited:
Look at the last sentence of my previous post.

Then try running your code going through all the numbers from 1 to 10. You'll notice the last digit of all your answers will be 0. This is incorrect.
 
Hey guys, thanks for the replies.

Im just trying to work through an exercise and it says i have to try and implement the method recursively and not use iteration. Just slightly puzzled now, i can understand what you guys are saying. If only there was a way to reverse the output, that way the zero on the rsh would be irrelevant in binary if you were reading from right to left.

Hope you understand what im trying to say.:)
 
If only there was a way to reverse the output, that way the zero on the rsh would be irrelevant in binary if you were reading from right to left.

Hope you understand what im trying to say.:)
Actually, binary numbers starting with 0 are negative ;).

and maybe new StringBuffer(decTobin(int n)).reverse()) would work :p.
 
It worked :D...i could have sworn i tried that, i remember getting some compilation error about not being able to get to the bit after the method is called recursively..

Thanks guys :D

Now i need to try and implement binary to decimal...lol i'll get back to you most likely as i will probably get stuck with that too..
 
Back
Top Bottom