我的十进制到二进制转换器有问题。我正在使用字符串来获取一个数字,然后我运行循环来查找“1”。它完成了这项工作,但最后打印了太多的零。我应该寻找什么来摆脱过多的 0 的任何想法?
System.out.print("Please enter Decimal number: ");
int decimalNum = kybd.nextInt();
power = 0;
expo = 2;
sum = 0;
String finalNumber = "";
for (int i = decimalNum; i >= 1; i--)
{
if(decimalNum%2 != 0)
{
finalNumber += '1';
}
else
finalNumber += '0';
decimalNum = decimalNum/2;
}//end of decimalLoop
for(int i = finalNumber.length()-1; i>=0; i--)
{
if(finalNumber.charAt(i)== '1')
{
//finalNumber = finalNumber + finalNumber.charAt(i);
System.out.print(finalNumber.charAt(i));
}
else
//finalNumber = finalNumber + finalNumber.charAt(i);
System.out.print(finalNumber.charAt(i));
}
请输入十进制数:10
0000001010