gpt4 book ai didi

c# - 奇怪的字符串操作方法

转载 作者:行者123 更新时间:2023-12-01 14:11:10 26 4
gpt4 key购买 nike

我的同事试图编写一个方法(在 Java/C# 中),该方法将在 String 的末尾附加任意数量的零。 。但是,我似乎无法弄清楚他的方法是什么。

这是Java代码,C#基本上是等价的:

String appendzeros(int input, int no_of_digits_required)
{
String result = Integer.toString(input);
int i,j;

for(i = 10, j = 1; i <= Math.pow(10, no_of_digits_required-1); i = i*10, j++)
{
if(input / i == 0)
{
for(int k = 1; k <= no_of_digits_required-j; k++)
result = "0" + result;

break;
}
}

return result;
}

有什么想法吗?

最佳答案

该代码的基本思想是计算字符串化数字中有多少位数字,然后添加“填充”零。

现在让我们看看如何...

String result = Integer.toString(input);

数字的初始字符串化 ( 5 => "5" )

for(i = 10, j = 1; i <= Math.pow(10, no_of_digits_required-1); i = i*10, j++)

i将包含 10 的幂 (10, 100, 1000, 10000, 100000....) 我们知道我们可以停在 10^(no_of_digits_required-1) 。为什么?我们稍后会看到! jinput 的位数(它是一个计数器,我们知道它至少有一个数字,因为即使是0也是由数字组成的)

if(input / i == 0)

不要看你所看到的...想一下:这意味着:第一次i大于input 。这是因为我们使用整数除法,所以任何数字/任何较小的数字> = 1,而任何数字/相同的数字== 1和任何数字/更大的数字== 0。(第一次是因为在if中)有一个 break ,所以第一次之后, for 循环就会结束)

for(int k = 1; k <= no_of_digits_required-j; k++)
result = "0" + result;

j我们有号码的位数,所以 no_of_digits_required-j0 的数量我们需要的填充。他正在使用1 <= k <= no_of_digits_required-j ,所以基数为 1,而不是更经典的 0 <= k < no_of_digits_required-j (基数为 0)

break;

我们仍在if内。当我们第一次找到我们的数字中有多少位数字时,我们填充它,然后我们得到“正确”的结果,然后我们从“主” for 中脱离出来。 .

现在唯一有趣的问题是为什么 Math.pow(10, no_of_digits_required-1) 。答案很简单:如果您询问 no_of_digits_required == 1 ,那么循环就没用了,因为你永远不需要填充。 i = 10 , i <= 10^(1-1) => i <= 1 ,没有for循环。与no_of_digits_required == 2我们有i = 10 , i <= 10^(2-1) => i <= 10 ,所以一个循环。这没问题,因为只有当数字 < 10 时我们才需要填充该数字(即 0...9)。 if (input / i == 0)事实上,仅对 0...9... 范围内的输入“激活”,依此类推。

我认为你的前同事已经准备好参加混淆 C 竞赛了!

关于c# - 奇怪的字符串操作方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18512366/

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