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
 
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? :(
 
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.:)
 
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..
 
Is it? I'm already stuck lol :P

Basically do i have to try and implement using a charAt on each character of the binary string...if the character is 1 then what do i do mathematicaly? I know how to do it mentaly but im not sure how java would do it if you know what i mean?

Thanks
 
Hey guys...with binary to decimal i have the same problem as before, the input is read from right to left instead of left to right therefore the wrong decimal number is calculated. Im stumped with how to change it, here is my code:

Code:
public static int binTodec (String b){
  
    int l = b.length()-1;
    int dec = 0;
    for (int i = l; i >= 0; i--)
    {
      int power = 1;
      for (int p = 1; p <= i; p++)
     {
       power = power * 2;
     }
    if (b.charAt(i) == '1')
    {
      dec = dec + power;
    }
  }
    return dec;
  }
 
Last edited:
Back
Top Bottom