java - 有什么办法可以去掉两端多余的 0's from the end of array when using Arrays.toString() and also the square brackets ' [ ]' 吗?

标签 java arrays

我编写了一个程序将十进制整数转换为二进制格式:

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/

相关文章:

java - 数组声明的差异

java - 我如何知道 Oracle 诊断包和 Oracle 调优包是否随 Oracle 安装一起安装?

java - 如何创建由多个图像组成的位图?

java - 大对角矩阵之和 JAVA

javascript - 如何防止数组中的重复项?

javascript - 我需要反转对象的格式

Java - 以编程方式剪切字符串

java - 为什么这会导致 tomcat 显示 jsp 源而不是实际呈现 html?

python - 将两个子字符串之间的字符串信息存储到数组中

javascript - 在 React 组件渲染中初始化一个数组(性能方面)