Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems.
This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to print the n-th digit of this string (digits are numbered starting with 1.
Input
The only line of the input contains a single integer n (1 ≤ n ≤ 1000) — the position of the digit you need to print.
Output
Print the n-th digit of the line.
문자열 만들어서 그 문자열의 index로 바로 접근했다.
입력이 1000밖에 안 돼서 O(n)으로 짜도 충분하다.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
using i64 = long long;
int main() {
int n;
scanf("%d", &n);
string s = "";
for(int i = 1; i <= 1000; i++){
s += to_string(i);
}
printf("%c", s[n-1]);
return 0;
}
문자열 1000까지 안 만들어도 됐을 것 같았는데 어느정도까지 만들지 감이 안 잡혀서 그냥 1000까지 더했다.
그 후 n-1번째 문자를 출력하면 된다~~
int를 string으로 만드는 함수 전에 찾아본 것 같은데 기억 안 나서 구글링했다. to_string()이었다. (아마)
int main()
{
int n;
scanf("%d", &n);
string s;
for (int i = 1; i <= n; i++)
s += to_string(i);
printf("%c\n", s[n - 1]);
return 0;
}
헉?? 코드가 완전 똑같다.
그리고 to_string 맞았구나! 전에 다른거 썼었는데 그건 뭐였지? 모르겠다. 나한테는 to_string()뿐이다. 또 string 항상 ""로 초기화해줘야 하는줄 알았는데 안 해도 되구나.
'코드포스' 카테고리의 다른 글
[코드포스 Practice4] C. Ohana Cleans Up (0) | 2019.11.20 |
---|---|
[코드포스 Practice4] B. Middle of the Contest (0) | 2019.11.19 |
[코드포스 Practice4] 후기 (0) | 2019.11.19 |
[코드포스 Practice3] C. Serval and Toy Bricks (0) | 2019.11.19 |
[코드포스 Practice3] A. Uniform String (0) | 2019.11.16 |