[英]Converting binary to Binary String: leading zero
I keep getting 0 in front of the resulting binary. 我总是在生成的二进制文件前面得到0。
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
: 解决此问题的一种方法是在testSubject < 2
立即停止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/ 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.