【leetcode】390. 消除游戏

int lastRemaining(int n){
    return (n==1)?1 :2 * (n/2 - lastRemaining(n/2) + 1);
}

 

int lastRemaining(int n){
    int stack[100]={0}, pst=-1, i, res=1;
    for(i=0; n>1; i++){
        if (i%2==0)
            stack[++pst]=2;
        else{
            stack[++pst]=(n%2)?2 :1;
        }
        n/=2;
    }
    for (i=pst; i>=0; i--){
        res=(stack[i]==2)?res*2 :res*2-1;
    }
    return res;
}

 

posted @ 2021-02-04 16:29  温暖了寂寞  阅读(60)  评论(0编辑  收藏  举报