【问题标题】:left rotation operation in c++c++中的左旋转操作
【发布时间】:2021-04-26 10:10:23
【问题描述】:
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] << " ";
}

我想向左旋转 10 个数字,"shiftSteps" 是向左移动的次数。但是我有一个问题,到目前为止,我为某些数字编写的代码可以正常工作,例如{0 1 2 3 4 5 6 7 8 9} and shiftSteps = 3 输出为3 4 5 6 7 8 9 0 1 2。 但如果输入为0 1 2 3 4 5 6 7 8 9shiftSteps = 15,则输出为5 6 7 8 9 5 6 7 8 9 和0 消失,shiftSteps = 15 的正确答案是5 6 7 8 9 0 1 2 3 4

【问题讨论】:

标签: c++ rotation


【解决方案1】:

问题是newposition = i - shiftSteps + 10; 导致shiftSteps == 15i &lt; 5 的值为负。这会导致越界访问。

需要保证旋转量小于数组元素个数,可以通过取模算子来实现。

    shiftSteps = shiftSteps % 10;

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

这适用于shiftSteps 的非负值。如果你还需要处理负数,你应该相应地调整循环中的条件。

PS:另外,请注意在您的代码中 shiftSteps 未初始化。

PPS:您也可以使用std::rotate 算法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 2013-09-15
    • 1970-01-01
    相关资源
    最近更新 更多