eyas小猪

导航

JAVA 十进制二进制互转 递归方法

public class test {

    public static void main(String[] args) {
        
           System.out.println("位数:"+binary(35)+"\n二进制:"+strNum);
           decimal("100011");           
           System.out.println("十进制:"+dl);
           
    }    
    private static String strNum="";
    private static int binary(int decimal) {        
        if(decimal%2!=0)
        {
            strNum="1"+strNum;
        }else {            
            strNum="0"+strNum;            
        }
        if (decimal/2==0) {            
            return 1;
        }        
        return 1+binary(decimal/2);     
         
    }
    private static int num=1;
    private static int dl=0;
    private static void decimal(String binary)
    {        
        if(binary.substring(binary.length()-num,binary.length()-num+1).equals("1")) {
            if(num==1)
            {
                dl+=1;
            }
            else {
                int z=1;
            for (int i = 1; i < num; i++) {
                z=z*2;
            }
            dl+=z;
            }
        }
        ++num;
        if (num>binary.length()) {
            return;
        }
        decimal(binary);
    }

 

posted on 2017-12-28 17:59  eyas小猪  阅读(1096)  评论(0编辑  收藏  举报