2582 - Pass the Pillow

 JAVA

  • class Solution {
        public int passThePillow(int n, int time) {
            int ans = 1, k = 1;
            while (time-- > 0) {
                ans += k;
                if (ans == 1 || ans == n) {
                    k *= -1;
                }
            }
            return ans;
        }
    }

C++

  • class Solution {
    public:
        int passThePillow(int n, int time) {
            int ans = 1, k = 1;
            while (time--) {
                ans += k;
                if (ans == 1 || ans == n) {
                    k *= -1;
                }
            }
            return ans;
        }
    };
    

Comments