C Language Programming Tutorial (Third Edition) Homework 10.5 (C++) kkmd66

difficulty


1. Solve according to the process, you can get the correct answer, but time out, the first piece of code; 2. Use the solution of Joseph ring to solve, you can pass, the second piece of code;


Description:

There are n people in a circle, numbered in order. Start counting from the first person (counting from 1 to 3), all those who report to 3 leave the circle and ask who is the original number left at the end.

Input:

Contains multiple sets of data.

Each row represents the initial number of people n.

The last group is 0 and does not need to be processed.

Output:

Output the initial number of the last person for each test data

Sample Input:

3
7
0

Sample Output:

2
4

#include <iostream>
#include "string"

using namespace std;

/**
 * kkmd66
 * @return
 */

int main() {
    
    

    int n;
    while (cin >> n && n != 0) {
    
    

        //输入数据
        string str;
        for (int i = 1; i <= n; ++i) {
    
    
            string c = to_string(i);
            str += c;
        }

        //依次踢出
        int pos = 0;
        while (str.size() > 1) {
    
    
            for (int i = 0; i < 2; ++i) {
    
    
                if (pos > str.size() - 1)
                    pos = 0;
                else
                    pos++;
                if (pos > str.size() - 1)
                    pos = 0;
            }
            if (pos > str.size() - 1)
                pos = 0;

            str.erase(pos, 1);

            if (pos > str.size() - 1)
                pos = 0;

        }

        //输出
        cout << str[0] << endl;

    }
    return 0;
}

#include <iostream>

using namespace std;

/**
 * kkmd66
 * 约瑟夫环
 * @return
 */

int main() {
    
    
    int n;
    while (cin >> n && n != 0) {
    
    
        
        int result = 0;
        
        //约瑟夫环
        for (int i = 2; i <= n; i++) {
    
    
            result = (result + 3) % i;
        }
        cout << result + 1 << endl;
    }
    return 0;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324105082&siteId=291194637