简体   繁体   中英

Converting binary to Binary String: leading zero

I keep getting 0 in front of the resulting binary.

  public static String convertToBinaryString(int testSubject){


    if(testSubject == 0){
      return binaryString = "0"; 
    }

    else{
      return convertToBinary(testSubject / 2) + "" + testSubject % 2;
    }

  }

How do I get rid of the leading zero?

One way to fix this is to stop recursing as soon as testSubject < 2 :

if (testSubject < 2) {
    return "" + testSubject % 2;
} else {
    return convertToBinary(testSubject / 2) + "" + testSubject % 2;
}

you could use build in function

   int x = 50;
    String s = Integer.toBinaryString(x);
    return s;

https://www.geeksforgeeks.org/java-lang-integer-tobinarystring-method/

There are other simpler ways of doing it. Your program has recursion overhead, which can be prevented using simple loop.

public static String convertToBinary(int testSubject) {
    // Method 1
    //   return Integer.toBinaryString(testSubject);

    // Method 2
    String str = "";
    while(testSubject!=0) {
      str = testSubject%2 + str;
      testSubject/=2;
    }
    return str;
  }

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