사자자리
[C언어] 백준 8595번: 히든 넘버 본문
https://www.acmicpc.net/problem/8595
8595번: 히든 넘버
첫째 줄에 단어의 길이 n (1 ≤ n ≤ 5,000,000)이 주어진다. 둘째 줄에는 단어가 주어진다. 단어는 알파벳 대/소문자와 숫자(0-9)로 이루어져 있다.
www.acmicpc.net
#include <stdio.h>
int main(){
int n;
char c;
long long int sum = 0, hidden = 0;
scanf("%d\n", &n);
while ((c = getchar()) != '\n'){
if ('0' <= c && c <= '9'){
hidden *= 10;
hidden += c - '0';
}
else{
sum += hidden;
hidden = 0;
}
}
sum += hidden;
printf("%lld", sum);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(){
int n, index = 0;
long long count = 0;
char hidden[7];
scanf("%d", &n);
char *word = malloc(sizeof(char)*n);
scanf("%s", word);
for (int i = 0; i < n; i++){
if (isdigit(word[i]) != 0 && i != (n-1)){
hidden[index] = word[i];
index++;
}
else if (isdigit(word[i]) != 0 && i == (n-1)){
hidden[index] = word[i];
count += atoll(hidden);
}
else if (isdigit(word[i]) == 0 && isdigit(word[i-1]) != 0){
count += atoll(hidden);
index = 0;
for (int j = 0; j < 7; j++) hidden[j] = '\0';
}
}
printf("%lld", count);
return 0;
}
[코드 설명]
문자열 word[i]를 4가지 경우로 나누었다.
1. word[i]가 숫자이고, i가 마지막이 아닐 때
- word[i]를 hidden 문자열에 저장한다.
- word[i+1]가 숫자일 수도 있으니, index++를 한다.
2. word[i]가 숫자이고, i가 마지막일 때
- word[i]를 hidden 문자열에 저장한다.
- 마지막이므로 hidden 문자열을 숫자로 바꾸고 count에 더한다.
3. word[i]가 문자이고, word[i-1]가 숫자일 때
- 숫자가 끝났으므로, hidden 문자열을 숫자로 바꾸고 count에 더한다.
4. 기타(word[i]가 문자이고, word[i-1]도 문자일 때 등)
[예시]
<입력>
6
ab12c3
<과정>
i | word[i] | hidden[i] | count |
i = 0 | a | NULL | 0 |
i = 1 | b | NULL | 0 |
i = 2 | 1 | hidden[0] = 1 | 0 |
i = 3 | 2 | hidden[1] = 2 | 0 |
i = 4 | c | NULL | 12 |
i = 5 | 3 | hidden[0] = 3 | 15 |
<출력>
15
'C언어 > C언어 문제' 카테고리의 다른 글
[C언어] 백준 2439번: 별 찍기 - 2 (0) | 2022.08.11 |
---|---|
[C언어] 백준 3060번: 욕심쟁이 돼지 (0) | 2022.08.11 |
[C언어] 백준 5211번: 가단조와 다장조 (0) | 2022.08.04 |
[C언어] 백준 10989번: 수 정렬하기 3 (0) | 2022.08.03 |
[C언어] 백준 1159번: 농구 경기 (0) | 2022.08.03 |
Comments