[LeetCode]390. Elimination Game

来源:互联网 发布:hive sql insert into 编辑:程序博客网 时间:2024/05/29 21:16

https://leetcode.com/problems/elimination-game/#/description


从左往右和从右往左交替删除数字,求最后留下的数字是什么






step是head移动步长,当是从左向右 或 (从右向左 && 剩余数字数目为奇数)head右移step位

public class Solution {    public int lastRemaining(int n) {        boolean left = true;        int remain = n;        int head = 1;        int step = 1;        while (remain > 1) {            if (left || remain % 2 == 1) {                head = head + step;            }            step *= 2;            remain /= 2;            left = !left;        }        return head;    }}


0 0
原创粉丝点击