赞
踩
[编程题]删数
有一个数组 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),为数组成员数
输出描述:
一行输出最后一个被删掉的数的原始下标位置。
输入例子1:
8
输出例子1:
6
输入例子2:
1
输出例子2:
0
- import java.util.*;
-
- public class Main {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- while(sc.hasNextInt()) {
- int n = sc.nextInt();
- LinkedList<Integer> queue = new LinkedList<>();
- for(int i = 0; i < n; i++) {
- queue.addLast(i);
- }
- while(queue.size() > 1) {
- queue.addLast(queue.getFirst());
- queue.removeFirst();
- queue.addLast(queue.getFirst());
- queue.removeFirst();
- queue.removeFirst();
- }
- System.out.println(queue.getFirst());
- }
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。