我编写了一个程序将十进制整数转换为二进制格式:
int b=17,i=0;
int s[]=new int[10];
while(b>0)
{
s[i]=(b%2);
b=b/2;
i++;
}
System.out.println(Arrays.toString(s));
打印:[1, 0, 0, 0, 1, 0, 0, 0, 0, 0]
但我想要“10001”作为输出,为此,使用 while() 循环,
int j;
for(j=i-1;j>=0;j--)
{
System.out.print(s[j]);
}
这会打印:“10001”,正如我想要的,但是有没有其他方法可以在不使用循环的情况下获得此输出?
或者
有没有办法删除[1, 0, 0, 0, 1, 0, 0, 0, 0, 0]中1,0,0,1之后多余的0?
最佳答案
从一开始就没有数组,并将结果附加到String
。这将消除数组到String
的转换。
int b=17;
String result = "";
while(b>0)
{
result = (b%2) + result;
b=b/2;
}
System.out.println(result);
String
也是字符数组,因此在内部您不会回避任何数组。
正如 @DodgyCodeException 所指出的,int 到二进制的原始 OP 代码正在生成反向的二进制字符串/数组。上面的代码已经修复了。
关于java - 有什么办法可以去掉两端多余的 0's from the end of array when using Arrays.toString() and also the square brackets ' [ ]' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60451929/