[LeetCode] Find the Child Who Has the Ball After K Seconds

3178. Find the Child Who Has the Ball After K Seconds

You are given two positive integers n and k. There are n children numbered from 0 to n - 1 standing in a queue in order from left to right.

Initially, child 0 holds a ball and the direction of passing the ball is towards the right direction. After each second, the child holding the ball passes it to the child next to them. Once the ball reaches either end of the line, i.e. child 0 or child n - 1, the direction of passing is reversed.

Return the number of the child who receives the ball after k seconds.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int numberOfChild(int n, int k) {
int res = 0, pos = 1;
while(k) {
if(0 <= res + pos and res + pos < n) {
res += pos;
k--;
} else pos = -pos;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/06/09/PS/LeetCode/find-the-child-who-has-the-ball-after-k-seconds/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.