gpt4 book ai didi

c# - 按索引返回数字的方法

转载 作者:行者123 更新时间:2023-12-03 19:22:14 24 4
gpt4 key购买 nike

我想编写一个方法,在不使用时按索引(place)返回数字(num)的数字 仅数组循环和条件。

例如:

  1. 对于输入 num = 17489place = 1,该方法返回 9
  2. 但是如果索引不存在,如num = 17489place = 6返回-1

如果我设置 i = 0,我的代码中的某些内容不起作用 情况 1) 有效,但 2) 不行如果我设置 i = 1 情况 2) 有效,但 1) 不行请帮忙找出问题所在

    public static int Digit_by_place(int num, int place)
{
int digit = 0, i = 0;

// the lop run until the place in the
while (num > 0 && i <= place)number
{
digit = num % 10;
num = num / 10;
i++;

// if there is no didgit in the input place return -1
if (i < place && num == 0)
{
return -1;
}

// return the last digit from left (the bigest)
if (num == 0 && digit > 0 && i == place)
{
return digit;
}
}

return digit;
}

最佳答案

我们可以利用 int 最多可以有 10 位数字这一事实。

代码:

public static int Digit_by_place(int num, int place) {
if (place <= 0 || place > 10) // place must be in [1..10] range
return -1;
else if (num == 0) // special case num == 0
return place == 1 ? 0 : -1;

for (int i = 1; i < place; ++i)
num /= 10;

return num == 0 ? -1 : Math.Abs(num % 10);
}

演示:

using System.Linq;
...

Tuple<int, int>[] tests = new Tuple<int, int>[] {
Tuple.Create( 17489, 1),
Tuple.Create( 17489, 2),
Tuple.Create( 17489, 3),
Tuple.Create( 17489, 4),
Tuple.Create( 17489, 5),
Tuple.Create( 17489, 6),
Tuple.Create(-17489, 1),
Tuple.Create(-17489, 6),
Tuple.Create( 17489, 0),
Tuple.Create( 17489, -1),
Tuple.Create(-17489, -1),
Tuple.Create( 17489, 5),
Tuple.Create(-17489, 5),
Tuple.Create( 0, 1),
Tuple.Create( 0, 4),
};

var report = string.Join(Environment.NewLine, tests
.Select(test =>
$"Digit_by_place({test.Item1,6}, {test.Item2,2}) = {Digit_by_place(test.Item1, test.Item2),2}"));

Console.Write(report);

结果:

Digit_by_place( 17489,  1) =  9
Digit_by_place( 17489, 2) = 8
Digit_by_place( 17489, 3) = 4
Digit_by_place( 17489, 4) = 7
Digit_by_place( 17489, 5) = 1
Digit_by_place( 17489, 6) = -1
Digit_by_place(-17489, 1) = 9
Digit_by_place(-17489, 6) = -1
Digit_by_place( 17489, 0) = -1
Digit_by_place( 17489, -1) = -1
Digit_by_place(-17489, -1) = -1
Digit_by_place( 17489, 5) = 1
Digit_by_place(-17489, 5) = 1
Digit_by_place( 0, 1) = 0
Digit_by_place( 0, 4) = -1

关于c# - 按索引返回数字的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53883772/

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