반응형
요즘 넘 중구난방으로 했엇는데.. 방학 계획 난이도 별로 C언어 일단 1단계부터 다 해야겠음
약수의 합
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int solution(int n) {
int answer = 0;
for(int i =1;i<=n;i++){
if(n%i==0){
answer+=i;
}
}
return answer;
}
자릿수 더하기
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int solution(int n) {
int answer = 0;
int i=100000000;
while(i>0){
if(n>i){
answer+=n/i;
n%=i;
}
i/=10;
}
return answer;
}
//틀린답
처음에 이렇게 입력했는데 test에서는 넘어갔는데 실제 결과 입력에서 실패가 몇개떴다..
다시 보니 while문에서 n이랑 i를무조건 다른걸 가정하고 해서 틀린거같다.. 같을 때도 나눠야 대는데..
그래서 고쳐서 하니까 맞음
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int solution(int n) {
int answer = 0;
int i=100000000;
while(i>0){
if(n>=i){
answer+=n/i;
n%=i;
}
i/=10;
}
return answer;
}
근데 찾아보니 내가 문제를 어렵게 푼거같음. 더 쉬운 풀이도 있다..
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int solution(int n) {
int answer = 0;
while (n > 0) {
answer += n % 10; // 현재 자릿수 더하기
n /= 10; // 다음 자릿수로 이동
}
return answer;
}
이렇게 하는게 더 효율적인 풀이일듯..
짝수와 홀수
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
char* solution(int num) {
// 리턴할 값은 메모리를 동적 할당해주세요
char* answer = (char*)malloc(5*sizeof(char));
if(num%2==0){
strcpy(answer, "Even");
}
else{
strcpy(answer, "Odd");
}
return answer;
free(answer);
}
처음 free(answer)를 return answer앞에 썼더니 계속 결과가 안나와서 머리 싸매고 잇었는데 메모리 해제를 결과값 전에 해서 그랬다.. 뒤로 순서 미루니까 결과가 맞게 나왔다.
평균 구하기
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
// arr_len은 배열 arr의 길이입니다.
double solution(int arr[], size_t arr_len) {
double answer = 0;
int sum=0;
for(int i=0;i<arr_len;i++){
sum+=arr[i];
}
answer = (double) sum / arr_len;
return answer;
}
sum을 int로 해두니까 아래 answer에 넣을 때 형변환해야댐
나머지가 1이 되는 수 찾기
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int solution(int n) {
int answer = 0;
for(int i=1;i<n;i++){
if(n%i==1){
answer=i;
break;
}
}
return answer;
}
반응형
'코딩해요 > C' 카테고리의 다른 글
[프로그래머스/C] 250128 코딩테스트 (0) | 2025.01.28 |
---|---|
[백준/C언어] 2475번: 검증수 (0) | 2024.07.09 |
[백준/C언어] 1193번: 분수찾기 (0) | 2024.07.09 |
[백준/C언어] 2292번: 벌집 (0) | 2024.07.09 |
[백준/C언어] 11005번: 진법 변환2 (0) | 2024.07.09 |