C++ 约瑟夫斯问题

需要注意:

循环移位没有数位丢失

循环左移时,左端移出位填充右端。

循环右移时,右端移出位填充左端。

//#include <bits/stdc++.h>
#define MaxSize 10000
using namespace std;
/*
* Created by HarvestWu on 2018/07/05.
*/

//获取n的二进制位数
int util(int n)
{
	int count = 0;
	while (n)
	{
		++count;
		n = n >> 1;
	}
	return count;
}

//约瑟夫斯问题
//即循环左移一次
int jose(int n)
{
	int l = util(n);
	int b = pow(2, l) - 1;
	return (n << 1 | n >> (l - 1))&b;
}

int main()
{
	int n;
	while (scanf("%d", &n) != EOF)
		printf("%d\n", jose(n));
	return 0;
}

猜你喜欢

转载自blog.csdn.net/harvestwu/article/details/80931666