Friday, December 25, 2015

Convert Numeric to Binary

With Recursion: 
    public StringBuffer convertToBinary(int n)    {
        if (n<2) return new StringBuffer().append(n);
        return new StringBuffer().insert(0, n%2).insert(0, convertToBinary(n/2));
    }


Without Recursion:
    public String convertToBinary(int n)    {
        StringBuffer result = new StringBuffer();
        while(n>0)    {
            result.insert(0, n%2);
            n=n/2;
        }
        return result.toString();
    }

No comments:

Post a Comment

UA-39217154-2