所以有 this博客给出了每个软件工程师都应该能够在不到 1 小时内解决的五个编程问题,我只是重温其中的一些概念。
第一题阅读
使用 for 循环、while 循环和递归编写三个函数来计算给定列表中数字的总和。
显然 for 和 while 循环很简单,但我从
int[] l = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
是否有可能从列表中弹出一个项目,然后每次都通过缩短的列表?
我在python中看到的一次尝试:
numbers = [1,2,3,4,5,6,7,8,9]
def recurse_count(lst):
if len(lst) == 1:
return lst[0]
else:
i = len(lst) - 1
subtotal = lst[i] + lst[i - 1]
lst.pop() #into the void with you
lst[-1] = subtotal
return recurse_count(lst)
在 C# 中使用 int[] 是否可行?
最佳答案
一个非常优雅的解决方案是:
static public int sumThisUp(IEnumerable<int> list)
{
return list.FirstOrDefault() + (list.Any() ? sumThisUp(list.Skip(1)) : 0);
}
关于C# 从整数列表中删除项目 int[] l = {1,2,3} - 或使用递归添加它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30143895/