删数

题目描述:

有一个数组a[N]顺序存放0~N-1,要求每隔两个数删掉一个数,到末尾时循环至开头继续进行,求最后一个被删掉的数的原始下标位置。以8个数(N=7)为例:{0,1,2,3,4,5,6,7},0->1->2(删除)->3->4->5(删除)->6->7->0(删除),如此循环直到最后一个数被删除。

输入描述:

每组数据为一行一个整数n(小于等于1000),为数组成员数,如果大于1000,则对a[999]进行计算。

输出描述:

一行输出最后一个被删掉的数的原始下标位置。

import java.util.ArrayList;
import java.util.Scanner;
 
public class Main
{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext())
        {
            int n = scanner.nextInt();
            int[] nums = new int[n];
            for (int i = 0; i < n; i++)
                nums[i] = i;
            ArrayList<Integer> del = new ArrayList<>();
            int i = -1;
            while (del.size() < n)
            {
                int count = 0;
                while (count < 3)
                {
                    i = (i + 1) % n;
                    if (nums[i] != -1 && count != 2)
                    {
                        count++;
                    }
                    else if (nums[i] != -1 && count == 2)
                    {
                        count++;
                        nums[i] = -1;
                        del.add(i);
                    }
                    else
                        continue;
                }
            }
            System.out.println(del.get(del.size() - 1));
        }
    }
}
import java.util.ArrayList;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext())
        {
            int n = scanner.nextInt();
            ArrayList<Integer> list = new ArrayList<>();
            for (int i = 0; i < n; i++)
                list.add(i);
            int index = 0;
            while (list.size() > 1)
            {
                index = (index + 2) % list.size();
                list.remove(index);
            }
            System.out.println(list.get(0));
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值