40.孩子们的游戏(圆圈中最后剩下的数)
题目内容:
代码及思路:
因为是环状的,因此从0开始,第m个数字时(m-1)%n
#include<iostream>
#include<vector>
using namespace std;
class Solution
{
public:
int LastRemaining_Solution(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 main()
{
Solution* object = new Solution;
vector<int> numbers;
int num;
char ch;
do
{
cin >> num;
numbers.push_back(num);
cin.get(ch);
} while (ch == ',');
int n = numbers.size();
int m;
cin >> m;
int res = object->LastRemaining_Solution(n, m);
cout << res << endl;
}