输出圆圈报数退出的最后号码.c 888 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int lastRemaining(int n, int m) {
  4. int *people = (int *)malloc(n * sizeof(int));
  5. int i;
  6. for (i = 0; i < n; i++) {
  7. people[i] = 1;
  8. }
  9. int remaining = n;
  10. int count = 0;
  11. int index = 0;
  12. for (i = 0; remaining > 1; i = (i + 1) % n) {
  13. if (people[index] == 1) {
  14. count++;
  15. if (count == m) {
  16. people[index] = 0;
  17. count = 0;
  18. remaining--;
  19. }
  20. }
  21. index = (index + 1) % n;
  22. }
  23. int result = 0;
  24. for (i = 0; i < n; i++) {
  25. if (people[i] == 1) {
  26. result = i + 1;
  27. break;
  28. }
  29. }
  30. free(people);
  31. return result;
  32. }
  33. int main() {
  34. int n, m;
  35. scanf("%d %d", &n, &m);
  36. int result = lastRemaining(n, m);
  37. printf("%d", result);
  38. return 0;
  39. }