gpt4 book ai didi

java - 有效打印长序列

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:34:04 24 4
gpt4 key购买 nike

我必须打印一个由 5 和 3 组成的巨大序列(最多 100,000 个整数)的数字。我没有将它存储在数组中,而是将它们的计数保存在 noOfThreesnoOfFives 中。

为简单起见,将此数字称为x。 .

因为我必须打印序列中最大的数字,x 最初是 5,然后是 3(如果没有 5 或没有 3,我有打印的工作逻辑)

为了打印数字,我使用了这样的 for 循环:

for(int i=0; i<noOfFives; i++) 
System.out.print(5);
for(int i=0; i<noOfThrees; i++)
System.out.print(3);

但是如果 x 是一个 100,000 长整型数字,它需要大约 4-5 秒才能在控制台上打印它,这是不可取的。

我的看法:

  • 如果 noOfFives 是偶数,则在 for 循环中打印 55,这会提高 x2 的性能并将循环递增 2,否则
  • 使用与上面相同的 for 循环。 noOfThrees 也是如此。

但这里的问题是如果它很奇怪,它会再次以步骤 1 结束打印。我如何有效地打印这个序列?

最佳答案

如果您认为 print 调用的次数是问题所在,您可以将其减少到 1:将正确数量的 3 和 5 放入一个字符数组中,然后打印:

char[] cs = new char[noOfFives + noOfThrees];
Arrays.fill(cs, 0, noOfFives, '5');
Arrays.fill(cs, noOfFives, cs.length, '3');
System.out.print(cs);

关于java - 有效打印长序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33515795/

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