0

As the title says i was trying to convert binary to decimal using recursive technique in java but i cannot get the desire output here's what i did

   public class deci {
       public static void main(String args[]){
           hexa s1=new deci();
           s1.spawn(11000);
       }
       void spawn(int a){
           int p=0;int x=0;int k=0;
           if(a>0){
               p=a%10;
               x=x+p*(int)Math.pow(2,k);
               k++;
               spawn(a/10);
           } else {
               System.out.print(x);
           }
       }
   }     
9
  • And what's the desired output? What output did you get? Make an effort, man. Commented Sep 18, 2013 at 14:26
  • i get 00110 instead of 12 Commented Sep 18, 2013 at 14:27
  • so what problem this code really has ?? Commented Sep 18, 2013 at 14:29
  • Well, you're not passing the value of k anywhere for one, so it's always 0. Commented Sep 18, 2013 at 14:30
  • 1
    @Sigma I won't write out the code for you, but I can help you with it. I already mentioned that you increment 'k', but never do anything with it. Commented Sep 18, 2013 at 14:39

2 Answers 2

1

The problem is you ar not using the result of spawn, either returning or printing it.

If you want to return it, you need the shifting or power, but it you want to print it.

I suggest you step through the code in your debugger so you can see what it is doing.

Sign up to request clarification or add additional context in comments.

Comments

0

Here is a working program.

Parameters are (binary code, size of code-1) e.g. for (111, 2) this will return 7

int binaryToDecimal(int binary,int size){  
  if(binary==0) return 0;        
  return binary%10*(int)Math.pow(2,size)+binaryToDecimal((int)binary/10,size-1);  
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.