题目

image.png

题解

  1. class Solution {
  2. public int lastRemaining(int n) {
  3. int head = 1;
  4. int step = 1;
  5. boolean left = true;
  6. //int n = n;
  7. while (n > 1) {
  8. //从左边开始移除 or(从右边开始移除,数列总数为奇数)
  9. if (left || n % 2 != 0) {
  10. head += step;
  11. }
  12. step *= 2; //步长 * 2
  13. left = !left; //取反移除方向
  14. n /= 2; //总数 / 2
  15. }
  16. return head;
  17. }
  18. }
  19. 作者:xing-you-ji
  20. 链接:https://leetcode-cn.com/problems/elimination-game/solution/wo-hua-yi-bian-jiu-kan-dong-de-ti-jie-ni-k2uj/
  21. 来源:力扣(LeetCode
  22. 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。