Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
902 views
in Technique[技术] by (71.8m points)

left rotation operation in c++

int main()
{
    int newposition, shiftSteps;
    int numbers[10], numberscopy[10];
    cin >> shiftSteps;
    for (int i = 0; i < 10; i++)
        cin >> numbers[i];

    for (int i = 0; i < 10; i++)
        numberscopy[i] = numbers[i];

    //------------------------------------

    for (int i = 9; i >= 0; i--)
    {
        if (i - shiftSteps < 10 && i - shiftSteps >= 0)
            newposition = i - shiftSteps;
        else
            newposition = i - shiftSteps + 10;
        numbers[newposition] = numberscopy[i];
    }
    for (int i = 0; i < 10; i++)
        cout << numbers[i] << " ";
}

I want to rotate 10 numbers to left and "shiftSteps" is number of moves to the left. but I have a problem, the code I wrote so far for some numbers it works properly like {0 1 2 3 4 5 6 7 8 9} and shiftSteps = 3 output is 3 4 5 6 7 8 9 0 1 2. but if inputs are 0 1 2 3 4 5 6 7 8 9 and shiftSteps = 15, the output is 5 6 7 8 9 5 6 7 8 9 and 0 Disappears, True answer for shiftSteps = 15 is 5 6 7 8 9 0 1 2 3 4.

question from:https://stackoverflow.com/questions/65836748/left-rotation-operation-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that newposition = i - shiftSteps + 10; results in a negative value for shiftSteps == 15 and i < 5. This results in an out-of-bounds access.

You need to ensure that the rotation amount is below the number of elements of the array, which can be achieved with a modulus operator.

    shiftSteps = shiftSteps % 10;

    for (int i = 9; i >= 0; i--)
    {
        newposition = i - shiftSteps;
        if (newposition < 0)
            newposition += 10;
        numbers[newposition] = numberscopy[i];
    }

This will work for non-negative values of shiftSteps. If you also need to handle negatives, you should adjust the condition in the loop accordingly.

PS: Also, note that in your code shiftSteps is left uninitialized.

PPS: You could also use std::rotate algorithm.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...