JZ46 Children's game (the last remaining number in the circle)

Title description

Every June 1st Children’s Day, Niuke will prepare some small gifts to visit the children in the orphanage, and this is also true this year. As a senior veteran of Niu Ke, HF naturally prepared some small games. Among them, there is a game like this: First, let the children form a big circle. Then, he randomly designated a number m, and let the child number 0 start to report the number. Every time the child who shouts m-1 has to go out and sing a song, and then he can choose any gift in the gift box, and he does not return to the circle again. Starting from his next child, continue 0...m-1 Report the number... Continue like this... Until the last kid is left, you don't need to perform, and get the valuable "Detective Conan" Collector's Edition (the quota is limited!! _ ). Please try to think, which kid will get this gift? (Note: Children’s numbers are from 0 to n-1)

If there are no children, please return -1

answer

public class Solution {
    
    
     public int LastRemaining_Solution(int n, int m) {
    
    
        if (n <= 0 || m <= 0) {
    
    
            return -1;
        }
        int ans = 0;
        for (int i = 2; i <= n; i++) {
    
    
            ans = (ans + m) % i;
        }
        return ans;
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41620020/article/details/108591616