1

I am writing a code to convert a number to binary representation.Here's my code.It doesn't give the correct answer but I can't figure out where I am making the mistake.If someone could point out where my mistake and how to correct it I would be grateful.

public class ConvertBinary{
    public static String convertBinary(int n){
        String s="";
        while(n>0){
            s+=(n%2);

            n=n/2;
        }


        int len=s.length();
        String[] binary=s.split("");
        String[] binaryCopy=new String[s.length()];

        for(int i=0;i<len;i++){
            binaryCopy[i]=binary[len-i-1];
            s+=binaryCopy[i];
        }
        return s;

    }

    public static void main (String args[]){
        System.out.println(convertBinary(19));
    }
}
2
  • 1
    Is there a reason not to use docs.oracle.com/javase/7/docs/api/java/lang/… ? Commented May 14, 2014 at 14:22
  • 1
    There’s even Integer.toBinaryString(…). But if you insist of doing it manually, why are you using s += … with that mind-twisting reverse operation, rather than just using s = … + s to prepend the digit right in the first place? Commented May 14, 2014 at 14:24

4 Answers 4

1

Apart from all these answers the problem with your code was that you are not clearing the string before reversing it. So before the for loop just put s = "" and you code should work fine.. :)

Based on comment

public class ConvertBinary {
    public static String convertBinary(int n) {
        String s = "";
        while (n > 0) {
            s += (n % 2);

            n = n / 2;
        }

        int len = s.length();
        String[] binary = s.split("");
        String[] binaryCopy = new String[s.length()];

        s = "";

        for (int i = 0; i < len; i++) {
            binaryCopy[i] = binary[len - i - 1];
            s += binaryCopy[i];
        }
        return s;

    }

    public static void main(String args[]) {
        int num = 4;
        System.out.println(convertBinary(num));
        System.out.println(Integer.toBinaryString(num));
    }
}
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks a lot.Bur=t still one element doesn't get printed.Say I want to convert 4, what it gets printed out is 00, instead of 001
Firstly binary of 4 is 100 and not 001. :) Beside that are you sure its printing wrong? I just copy pasted and executed the code and it works fine with 4. It does print 100.
I have to make in the for loop i<=len instead of i<len.Then it works fine.But why?
I suppose you need not change anything. have a look at my answer update. Its your same code. I just put that s ="" and used Integer.toBinaryString to compare your result. Its works just fine with i<len
|
1
public static String convertBinary(int n){
        String s="";
        while(n>0){
            s+=(n%2);

            n=n/2;
        }



    return (new StringBuffer(s).reverse().toString());
}

Comments

1

If you're looking for error in your implementation, you'd rather put:

  s = (n % 2) + s;

isntead of

  s+=(n%2);

so the code'll be

  // n should be positive
  public static String convertBinary(int n){
    if (n == 0)
      return "0";

    String s = "";

    // for is more compact than while here
    for (; n > 0; n /= 2)
      s = (n % 2) + s;

    return s;
  }

however in real life

  Integer.toString(n, 2);

is much more convenient

1 Comment

Thanks.I didn't think of prepending the digit
0

Use Java standard library: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString%28int,%20int%29

public class ConvertBinary{
    public static String convertBinary(int n){
        return Integer.toString(n, 2);
}

    public static void main (String args[]){
        System.out.println(ConveryBinary.convertBinary(19));
    }
}

EDIT: As @Holger says, there's also a toBinaryString: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toBinaryString%28int%29

public static String convertBinary(int n){
    return Integer.toBinaryString(n);
}

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.