题目:0,1,...,n-1这n个数字排成一个圆圈,从数字0开始每次从这个圆圈里删除第m个数。求出这个圆圈里剩下的最后一个数字。
#include <iostream>
#include <list>
using namespace std;
int LastRemain(int n ,int m)
{
if(n < 1 || m < 1)
return -1;
list<int> number;
for(int i = 0;i < n; i++)
{
number.push_back(i);
}
list<int>::iterator current = number.begin();
while(number.size() > 1)
{
for(int i=1; i<m; i++)
{
current++;
if(current == number.end())
current = number.begin();
}
list<int>::iterator next = ++current;
if(next == number.end())
next = number.begin();
--current;
number.erase(current);
current = next;
}
return *(current);
}
int lastRemain(int n, int m)
{
if(n < 1 || m < 1)
return -1;
int last = 0;
for(int i =2; i <= n; i++)
{
last = (last + m) % i;
}
return last;
}
// ====================测试代码====================
void Test(char* testName, unsigned int n, unsigned int m, int expected)
{
if(testName != NULL)
printf("%s begins: \n", testName);
if(LastRemain(n, m) == expected)
printf("Solution1 passed.\n");
else
printf("Solution1 failed.\n");
if(lastRemain(n, m) == expected)
printf("Solution2 passed.\n");
else
printf("Solution2 failed.\n");
printf("\n");
}
void Test1()
{
Test("Test1", 5, 3, 3);
}
void Test2()
{
Test("Test2", 5, 2, 2);
}
void Test3()
{
Test("Test3", 6, 7, 4);
}
void Test4()
{
Test("Test4", 6, 6, 3);
}
void Test5()
{
Test("Test5", 0, 0, -1);
}
void Test6()
{
Test("Test6", 4000, 997, 1027);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
return 0;
}