码迷,mamicode.com
首页 > 其他好文 > 详细

500个小朋友手拉手围成一个圈,依次按1、2、3报数,报到3的出列,最后一个留在圈里的是第几个?

时间:2020-02-21 20:45:41      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:stat   public   col   i++   pre   span   string   false   turn   

public class Count3Quit{
    
    //从数组的角度
    public void m1(){
        
        boolean[] child = new boolean[500];
        
        for(int i=0;i<child.length;i++){
            child[i] = true;
        }
        
        int count = 0;
        int left = child.length;
        int index = 0;
        
        while(left > 1){
            if(child[index]){
                count++;
            }
            if(count == 3){
                child[index] = false;
                left--;
                count = 0;
            }
            index++;
            if(index == 500){
                index = 0;
            }
        }
        
        for(int i=0;i<child.length;i++){
            if(child[i]){
                System.out.println(i);
            }
        }
    }
    
    //从类的角度
    public void m2(){
        Circle circle = new Circle(500);
        Child d = circle.first;
        int num = 0;
        while(circle.count > 1){
            num++;
            
            if(num == 3){
                circle.delete(d);
                num = 0;
            }
            d = d.right;
        }
        System.out.println(circle.first.index);
    }
    
        public static void main(String[] args){
        Count3Quit c = new Count3Quit();
        c.m1();
        c.m2();
    }
    
}

class Circle{
    
    int count = 0;
    Child first,end;
    
    public Circle(int num){
        for(int i=0;i<num;i++){
            add();
        }
    }
    
    void add(){
        Child c = new Child(count);
        if(count == 0){
            c.left = c;
            c.right = c;
            first = c;
            end = c;
        } else{
            c.left = end;
            end.right = c;
            end = c;
            c.right = first;
            first.left = c;        
        }
        count++;
    }
    
    void delete(Child c){
        if(count == 0){
            System.out.println("空空如也");
            return;
        } else if(count == 1){
            first = end = null;
        } else{
            c.left.right = c.right;
            c.right.left = c.left;
    
            if(c == first){
                first = c.right;
            } else if(c == end){
                end = c.left;
            }
        }
        count --;
    }
}

class Child{
    
    int index;
    Child left;
    Child right;
    
    public Child(int index){
        this.index = index;
    }
    
}

 

500个小朋友手拉手围成一个圈,依次按1、2、3报数,报到3的出列,最后一个留在圈里的是第几个?

标签:stat   public   col   i++   pre   span   string   false   turn   

原文地址:https://www.cnblogs.com/yxfyg/p/12342623.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!