有趣的一个循环数组问题

问题:假设有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
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值