작성일 :

문제 링크

6993번 - Shift Letters

설명

단어와 이동 칸 수가 주어질 때, 단어를 오른쪽으로 회전시켜 출력하는 문제입니다.


접근법

오른쪽으로 n칸 회전하면 뒤에서 n글자가 앞으로 이동합니다.

따라서 단어를 (길이 - n) 위치에서 자른 뒤, 뒷부분을 앞에 붙이면 회전된 결과가 됩니다.


Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Text;

class Program {
  static void Main() {
    var parts = Console.In.ReadToEnd().Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
    var idx = 0;
    var t = int.Parse(parts[idx++]);
    var sb = new StringBuilder();

    for (var i = 0; i < t; i++) {
      var w = parts[idx++];
      var n = int.Parse(parts[idx++]);
      var len = w.Length;
      var cut = len - n;
      var shifted = w.Substring(cut) + w.Substring(0, cut);
      sb.AppendLine($"Shifting {w} by {n} positions gives us: {shifted}");
    }

    Console.Write(sb);
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int t; cin >> t;
  for (int i = 0; i < t; i++) {
    string w; int n; cin >> w >> n;
    int len = (int)w.size();
    int cut = len - n;
    string shifted = w.substr(cut) + w.substr(0, cut);
    cout << "Shifting " << w << " by " << n << " positions gives us: " << shifted << "\n";
  }

  return 0;
}