https://www.acmicpc.net/problem/11720
단계별로 풀어보기 >> 문자열 파트에 도달했다
c++ 표준 라이브러리에서 제공하는 string 클래스를 요리조리 사용해보는 시간~
오늘 새롭게 알게된 점은 무엇인가!?
string str = "HELLO"
// str의 데이터 타입은 string이고
// str[0]의 데이터 타입은 char이다
공백 없이 입력받은 모든 숫자를 합하는 이번 문제에서 나의 로직은 이렇다
입력을 string으로 받고 string.size()만큼 반복문 돌려가지고 각각의 index로 접근해서 int로 변환시켜서 더해주자~
인터넷에 검색해보니 string to int 하려면 stoi(string 변수명) 요런 함수를 써야한다고 한다.
근디 string str[i] 요런식으로 넣으니께 안 되는것이었다!
알고보니 인덱스로 문자열에 접근하면 고것의 반환값은 char였다!
< 제출 코드 >
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
int N;
cin >> N;
string input;
cin >> input;
int answer = 0;
for(int i=0; i<input.size(); i++){
answer += input[i] - '0';
}
cout << answer;
}
p.s. N은 왜 입력받는것이죠..?
참고블로그
https://chanhuiseok.github.io/posts/algo-37/
알고리즘 - C++에서 문자열(string) 다루기
컴퓨터/IT/알고리즘 정리 블로그
chanhuiseok.github.io
'Algorithm > BOJ' 카테고리의 다른 글
| [백준/2908/c++] 상수 (0) | 2024.02.13 |
|---|---|
| [백준/10809/c++] 알파벳 찾기 (0) | 2024.02.13 |
| [백준/5597/c++] 과제 안 내신 분..? (0) | 2024.02.10 |
| [백준/27433/c++] 팩토리얼 2 (1) | 2024.02.05 |
| [프로그래머스/python] 외계어 사전 (0) | 2023.01.18 |