刷题总结#13

#390. Elimination Game
There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.

Repeat the previous step again, but this time from right to left, remove the right most number and every other number from the remaining numbers.

We keep repeating the steps again, alternating left to right and right to left, until a single number remains.

Find the last number that remains starting with a list of length n.

Input:
n = 9,
1 2 3 4 5 6 7 8 9
2 4 6 8
2 6
6

Output:
6

My solution:
当cnt次做左到右时,都是删除了奇数,剩下的数/2,就是n/2进行cnt+1次删除。 只有从右向左删才可能删除偶数,删除了偶数则剩下的数可以整理为y,y*2-1可以表示删除前的数。
n表示从1-n的数字,cnt表示第几次删减,奇数次为从左到右,偶数次从右到左

 int lastRemaining(int n) {
        return helper(n,1);
    }
    int helper(int n,int cnt)
    {
        if(n==1) return 1;   
        if(cnt%2==1)
        {
            return helper(n/2,cnt+1)*2;
        }
        else if(cnt%2==0)
        {
            if(n%2==0)
            {
                return helper(n/2,cnt+1)*2-1;
            }
            else
               return helper(n/2,cnt+1)*2;
        }
    }

#格雷码
The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:

public List<Integer> grayCode(int n) {
    List<Integer> result = new LinkedList<>();
    for (int i = 0; i < 1<<n; i++) result.add(i ^ i>>1);
    return result;
}
unsigned int binaryToGray(unsigned int num)
{
        return (num >> 1) ^ num;
}

/*
        The purpose of this function is to convert a reflected binary
        Gray code number to a binary number.
*/
unsigned int grayToBinary(unsigned int num)
{
    unsigned int mask;
    for (mask = num >> 1; mask != 0; mask = mask >> 1)
    {
        num = num ^ mask;
    }
    return num;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值