首页 > 编程语言 > 详细

有趣的一个循环数组问题

时间:2018-12-19 13:50:27      阅读:121      评论:0      收藏:0      [点我收藏+]

问题:假设有12个数字,1-12,每隔4个取出一个,到最后一位的时候则从第一位继续,知道不足四位,问取出的最后一位数字是多少?

乍一看,好像不难,然后我尝试着写,发现数组的序列index不好取,没辙,只好问问大神们,下面附上大神给出的代码

Queue<int> list = new Queue<int>(new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
int index = 1;
while (list.Count >= 4)
{
int nowInt = list.Dequeue();
if (index % 4 != 0)
list.Enqueue(nowInt);
else Console.WriteLine(nowInt);
index++;
}

大蛇用了队列实现,于是我想,直接用list站队是不是也可以?

List<int> arr = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
List<int> deleteArr = new List<int>();
int startIndex = 1;
while (arr.Count >= 4)
{
int currentInt = arr[0];
if (startIndex % 4 != 0)
{
arr.RemoveAt(0);
arr.Add(currentInt);
}
else
{
arr.RemoveAt(0);
deleteArr.Add(currentInt);
}
startIndex++;
}
foreach (var item in deleteArr)
{
Console.WriteLine(item);
}

得出的结果也是一样的,但是回过来想想这个题,我总是想着直接取4,8,12,,,位,却发现在末尾之后再连接第一位时,index就不好处理了,哎!!!还是菜,有木有大蛇有更好的方法?

有趣的一个循环数组问题

原文:https://www.cnblogs.com/JueYingHuang/p/10142703.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!