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));
    }
}
Syam S
  • 8,421
  • 1
  • 26
  • 36
sam_rox
  • 739
  • 3
  • 14
  • 29
  • 1
    Is there a reason not to use http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString%28int,%20int%29 ? – AntonH May 14 '14 at 14:22
  • 1
    There’s even [`Integer.toBinaryString(…)`](http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toBinaryString(int)). 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? – Holger May 14 '14 at 14:24

4 Answers4

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

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1
public static String convertBinary(int n){
        String s="";
        while(n>0){
            s+=(n%2);

            n=n/2;
        }



    return (new StringBuffer(s).reverse().toString());
}
pratim_b
  • 1,160
  • 10
  • 29
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));
    }
}
Syam S
  • 8,421
  • 1
  • 26
  • 36
  • 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 – sam_rox May 14 '14 at 14:48
  • 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. – Syam S May 14 '14 at 14:51
  • I have to make in the for loop i<=len instead of i – sam_rox May 14 '14 at 14:54
  • 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 – Syam S May 14 '14 at 14:58
  • Try binaryCopy[i] = binary[len - i]; –  May 14 '14 at 14:58
  • @Syam S:Yes binary of 4 is 100.It was a typo.Yes there's a problem.Always it prints out one digit less. – sam_rox May 14 '14 at 14:59
  • @Vivek Thachil :Isn't binary[len - i]; equivalent to if I make in the for loop i<=len. – sam_rox May 14 '14 at 15:02
  • In paper my for loop works.But the output always prints one digit less – sam_rox May 14 '14 at 15:06
  • @sam_rox For i<=len, when i=len, binary[len-i-1] = binary[-1] –  May 14 '14 at 15:43
  • 2
    Check these links on split.. http://stackoverflow.com/questions/10233210/java-split-string-on-empty-delimiter-returns-empty-string-at-the-beginning http://stackoverflow.com/questions/145509/why-does-abcd-startswith-return-true –  May 14 '14 at 15:49
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);
}
AntonH
  • 6,359
  • 2
  • 30
  • 40