b475簡單

步距漸變字輪

運用位置加權的模26循環,正確求解本題並處理邊界情況。

解題思路

把字母轉成0到25。第i個位置從1開始,位移為 K×i,結果編號為 (原編號+(K%26)×i)%26。

26格形成一圈,所以減去任意26倍都不改終點;每個位置各自轉換再串接。

時間 O(|S|),輸入與結果 O(|S|)。

Step-by-step animation

教學例子:教學字串 az,K=1,第一位a移1格。

回報動畫錯誤
步驟 1 / 3

步驟 1

教學字串 az,K=1,第一位a移1格。

a→b
狀態
b

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    string s;
    long long k;
    cin >> s >> k;
    k %= 26;
    for (int i = 0; i < (int)s.size(); i++)
        s[i] = 'a' + (s[i] - 'a' + k * (i + 1)) % 26;
    cout << s << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多