import java.util.List;
//50个人围成一圈到3和3的倍数时出圈,问剩下的人是谁?在原来的位置是多少?
/*思路:
* 1、首先把数据填充到数组或链表中
* 2、用一个while循环进行出圈,直到剩下一个元素留下。
*/
public class Cycle {
public static int cycle(int total, int k) {
List<Integer> dataList = new LinkedList<Integer>(); //创建链表对象
for (int i = 0; i < total; i++) { //添加数据元素
dataList.add(new Integer(i + 1));
}
//定义下标,模拟已经去掉一个元素,因此从-1开始
int index = -1;
//一直循环去除数据,直到剩下一个元素
while (dataList.size() > 1) {
index = (index + k) % dataList.size(); //得到应该出局的下标
dataList.remove(index--); //去除元素
}
return ((Integer)dataList.get(0)).intValue(); //返回它的值
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("该数字原来的位置是" + cycle(50, 3));
}
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号