简体   繁体   中英

Converting Binary Number to Decimal using recursion technique

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);
           }
       }
   }     

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.

Here is a working program.

Parameters are (binary code, size of code-1) eg 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);  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM