华为题库讲解(华为机试题-报数删除人)

题目描述:

有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出,问最后留下的那位是原来第几号。

思路分析:

首先是选好数据结构,轻量级的boolean数组,下边代表序号,全部初始化位true

退出变为false,设置全局变量int a,遍历数组,a (当对应为false时候,continue跳过)

遍历数组统计true的数量,为1时候退出

华为题库讲解(华为机试题-报数删除人)(1)

注意:

如果要用List来存储,注意遍历remove删除时候,要一致,不能list和iterator混用

代码:

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import java.util.Scanner;

public class Main {

static int all = 1;

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

while(scan.hasNext()){

int input = scan.nextInt();

if(input < 1){

return;

}else{

boolean[] persons = doCall(input);

for (int i = 0; i < persons.length; i ) {

if (persons[i]) {

System.out.println("最后留下的是:" (i 1) "号。");

}

}

}

}

}

public static boolean[] doCall(int person) {

boolean[] persons = new boolean[person];

int number = person, key = 0;

for (int i = 0; i < person; i )

persons[i] = true;

while (number != 1) {

for (int i = 0; i < person; i ) {

if (!persons[i]) {

continue;

} else {

key ;

if (key % 3 == 0) {

System.out.println("编号为:" (i 1) "的人退出。");

persons[i] = false;

}

}

}

number = 0;

for (int i = 0; i < person; i ) {

if (persons[i]) {

number ;

}

}

}

return persons;

}

}

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页