gpt4 book ai didi

java - 如何打印出数组表示的负数

转载 作者:行者123 更新时间:2023-12-01 07:05:57 25 4
gpt4 key购买 nike

我刚刚开始学习Java,我想尝试使用数组来表示大负数。

假设我有一个数组

[-2, 0, -5] and this represents the number -502

我尝试使用 StringBuilder,但它打印出来

-50-2

这是我现在的代码。有没有办法做到这一点,以便我可以附加第一个负数,然后在构建新字符串时跳过其余的负数?

    StringBuilder sb = new StringBuilder();

for(int x = arr.length-1; x>=0; x--){
sb.append(arr[x]);
}
String check = sb.toString();
System.out.println(check);

最佳答案

使用最后一个字符(带有适当的符号)初始化字符串缓冲区,然后忽略其余字符。

StringBuilder sb = new StringBuilder();
sb.append(arr[length-1]);

for (int x = arr.length-2; x>=0; x--) {
sb.append(Math.abs(arr[x]));
}
String check = sb.toString();
System.out.println(check);

关于java - 如何打印出数组表示的负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24451296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com