当前位置:网站首页>[pointer] solve the last person left

[pointer] solve the last person left

2022-07-06 14:36:00 |Light|

requirement

Yes n A circle of individuals , Sequence number . Count from the first person , Where to report 3 Of the people out of the circle , Make up a function , The last thing left is the original number .( Use a pointer to achieve )

Code

/* *  This function is used to calculate the last remaining bit  * n: The number of people in the enclosure  *  Return its number  */
int last_one(int n)
{
    
    int k=-1;
    int i,j,l=0;
    int a[n];
    for(i=0;i<n;i++)
    {
    
        a[i] = 0;
    }
    for(i=0;i<n-1;i++)
    {
    
        for(j=0;j<3;j++)
        {
    
            if(a[l]==1)
            {
    
                j--;
                l++;
                if(l==n)
                {
    
                    l=0;
                }
                continue;
            }
            if(j==2)
            {
    
                a[l]=1;
            }
            l++;
            if(l==n)
            l=0;
        }
    }
    for(i=0;i<n;i++)
    {
    
        if(a[i]==0)
        {
    
            k = i+1;
            break;
        }
    }
    return k;
}

main function

int main()
{
      
    int n;
    scanf("%d",&n);
    printf("%d\n",last_one(n));
    return 0;
} 

test

Test input
3
Output
2

原网站

版权声明
本文为[|Light|]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060918541494.html