在生成的二进制文件前面,我总是得到0。
public static String convertToBinaryString(int testSubject){
if(testSubject == 0){
return binaryString = "0";
}
else{
return convertToBinary(testSubject / 2) + "" + testSubject % 2;
}
}
如何去掉前导零?
发布于 2019-06-04 13:39:22
修复此问题的一种方法是在testSubject < 2
if (testSubject < 2) {
return "" + testSubject % 2;
} else {
return convertToBinary(testSubject / 2) + "" + testSubject % 2;
}
发布于 2019-06-04 13:57:17
你可以使用内建函数
int x = 50;
String s = Integer.toBinaryString(x);
return s;
https://www.geeksforgeeks.org/java-lang-integer-tobinarystring-method/
发布于 2019-06-04 14:02:06
还有其他更简单的方法。你的程序有递归开销,这可以使用简单的循环来避免。
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;
}
https://stackoverflow.com/questions/56437849
复制相似问题