Problem G: Throwing cards away II
Given is an ordered deck of n cards numbered 1 to nwith card 1 at the top and card n at the bottom.The following operation is performed as long as there are at least two cardsin the deck:Throw away the top card and move the card that is now on the top of thedeck to the bottom of the deck.
Your task is to find the last, remaining card.
Each line of input (except the last) contains a positive numbern ≤ 500000. The last line contains 0 and thisline should not be processed. For each number from input produceone line of output giving the last remaining card. Input will not containmore than 500000 lines.
Sample input
7 19 10 6 0
Output for sample input
6 6 4 4
题意:牌游戏,给出n,代表有n张牌,编号为1-n,1在顶部,n在底部,将最上方的牌先扔掉,然后再将此时最上方的牌放到底部,循环操作,问最后剩一张是什么值?
做法:拿张草稿算算就知道了,答案是有规律的,1 | 2 | 2 4 | 2 4 6 | 2 4 6 8 | 2 4 6 8 10 12 14 16 | ...
AC代码:
#include<stdio.h>
int main() {
int n;
while(scanf("%d", &n) != EOF && n) {
if(n == 1) {
printf("1\n");
continue;
}
int t = 1;
while(t * 2 < n)
t = t * 2;
n = n - t;
int ans = 0;
while(n--)
ans += 2;
printf("%d\n", ans);
}
return 0;
}