Official

A - A to Z String 2 Editorial by en_translator


If you are new to learning programming and do not know where to start, please try Problem A “Welcome to AtCoder” from practice contest. There you can find a sample code for each language.
Also, if you are not familiar with problems in programming contests, we recommend you to try some problems in “AtCoder Beginners Selection” (https://atcoder.jp/contests/abs).
「競プロ典型 90 問」(Typical 90 Problems of Competitive Programming) (https://atcoder.jp/contests/typical90) is a collection of typical 90 competitive programming problems; unfortunately, currently the problem statements are all Japanese.
「C++入門 AtCoder Programming Guide for beginners (APG4b)」(https://atcoder.jp/contests/APG4b) is a C++ tutorial for competitive programmers. Sadly, this is only in Japanese too.


As specified in the Problem Statement, construct the string and print the \(X\)-th character.

When constructing the string, it is easy to append one character by one. In C++, you may use push_back(); in python, you may use append().

When finding the \(X\)-th character, you may need to subtract \(1\) from \(X\) to convert one-based to zero-based numbering, because many languages adopt zero-based numbering where the first character is regarded as the \(0\)-th character, the succeeding was as the \(1\)-st, and so on.

Sample Code (C++)

#include<bits/stdc++.h>
using namespace std;

int main(){
    int n, x;
    cin >> n >> x;
    string s;
    for(int i = 0; i < 26; i++) {
        for(int j = 0; j < n; j++) {
            s.push_back('A' + i);
        }
    }
    x -= 1;
    cout << s[x] << endl;
}

Sample Code (python)

n, x = map(int, input().split())
s = []
for i in range(ord('A'), ord('Z') + 1):
    for j in range(n):
        s.append(chr(i))
print(s[x - 1])

In fact, you do not need to construct the string.

When \(X\) is either \(1,2,\ldots\), or \(N\), then the answer is A; if \(X\) is either \(N+1,N+2,\ldots\), or \(2N\), then the answer is B, …, and if \(X\) is either \(25N + 1, 25N+2,\ldots\), or \(26N\), then the answer is Z.

But this is too troublesome to implement, so let’s simplify it by using divisions. Let \(Y\) be the quotient when \((X-1)\) is divided by \(26\), rounded down, then the answer is A if \(Y=0\), B if \(Y=1\), …, and Z if \(Y=25\).

Therefore, it is sufficient to print \(Y\) letters after A.

The following is a sample code in C++ and Python.

Sample code (C++)

#include<bits/stdc++.h>
using namespace std;

int main(){
    int n, x;
    cin >> n >> x;
    int y = (x - 1) / n;
    cout << char('A' + y) << endl;
}

Sample code (python)

n, x = map(int, input().split())
print(chr(ord('A') + (x - 1) // n))

posted:
last update: