Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 비트마스크
- 조합
- 빠른 입출력
- SSAFY
- 세그먼트 트리
- 스택
- 백트래킹
- BeautifulSoup
- 피보나치 수
- 클래스
- 메모리풀
- 분할 정복
- 문자열
- 링크드리스트
- 그리디
- 재귀
- 순열
- 중복 순열
- 완전 탐색
- DP
- 이분 탐색
- dfs
- 시뮬레이션
- 큐
- Knapsack
- lis
- BFS
- 우선순위 큐
- 크루스칼
- MST
Archives
- Today
- Total
작심 24/7
[백준] 11720번 숫자의 합 본문
문자열을 정수로 변환하는 방법이 꽤 많았다.
그중 세 가지 방법으로 작성해보았다.
1. string으로 받고 '0'을 빼주어 정수로 변환
#include <iostream>
#include <string>
using namespace std;
int main() {
int N, sum = 0;
string st;
cin >> N >> st;
for (int i = 0; i < N; i++) sum += st[i] - '0';
cout << sum;
return 0;
}
2. string으로 받고 substr(시작 위치, 몇 개까지 추출할 건지) 함수를 이용해 나누기
#include <iostream>
#include <string>
using namespace std;
int main() {
int N, sum = 0;
cin >> N;
string a;
cin >> a;
for (int i = 0; i < N; i++) {
sum += atoi(a.substr(i, 1).c_str());
}
cout << sum;
return 0;
}
3. char형 배열로 받기
atoi()가 포인트형을 받는거라 배열이 들어가지 않아서 간접적으로 넣어줬다.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int N, sum = 0;
cin >> N;
char a[101], b[] = "0";
cin >> a;
for (int i = 0; i < N; i++) {
b[0] = a[i];
sum += atoi(b);
}
cout << sum;
return 0;
}
'백준' 카테고리의 다른 글
[백준] 1929번 소수 구하기 (2) | 2020.05.20 |
---|---|
[백준] 1193번 분수찾기 (0) | 2020.05.20 |
[백준] 15552 빠른 A+B (0) | 2020.05.20 |
[백준] 4839번 설탕 배달 (0) | 2020.05.20 |
[백준] 11648번 지속 (0) | 2020.05.20 |
Comments