如何解决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] << " ";
}
我想向左旋转 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 9
和 shiftSteps = 15
,则输出为 5 6 7 8 9 5 6 7 8 9
且 0 消失,shiftSteps = 15 的正确答案为 5 6 7 8 9 0 1 2 3 4
。
解决方法
问题是 newposition = i - shiftSteps + 10;
导致 shiftSteps == 15
和 i < 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
算法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。