인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

Inflearn Community Q&A

김영우's profile image
김영우

asked

Introduction to Algorithm Problem Solving for IT Employment (with C/C++): Coding Test Preparation

41. Sum of consecutive natural numbers (simple math)

문자열 처리

Written on

·

152

0

#include <stdio.h>
#include <algorithm>
#include <vector>

using namespace std;

int main(){
	int n, sum=0, cnt=0;
	int startPoint=1, endPoint=0;
	vector< vector<int> > results;
	
	scanf("%d",&n);
	
	//연산부 
	while(startPoint<(n/2)+1){
		for(int i=startPoint; i<n; i++){
			sum = sum + i;
			endPoint = i;
			if(sum>n){
				sum=0;
				startPoint++;
				break;
			}
			if(sum==n){
				vector<int>result;
				//시작지점부터 끝지점까지 자연수 추가 
				for(int q=startPoint; q<=endPoint; q++){
					if(q==endPoint) {
						result.push_back(endPoint);
						result.push_back(n); 
					}
					else {
						result.push_back(q);
					} 
				}
				results.push_back(result);
				sum=0;
				startPoint++;
				cnt++;
				break;
			}
		}
	}
	
	//출력부  
	for(int i=results.size()-1; i>=0; i--){
		for(int q=0; q<results[i].size(); q++){
			printf("%d",results[i][q]);
			if(q==results[i].size()-1){ 
				break;
			} else if(q==results[i].size()-2){
				printf(" = ");
			} else {
				printf(" + ");
			}
		}
		printf("\n");
	}	
	printf("%d",cnt);
	
	return 0;
}
C++코테 준비 같이 해요!

Answer 1

0

김영우님의 프로필 이미지
김영우
Questioner

문제와는 좀 다른 질문이긴 한데요.. 저 코드 작성하다 보니 개인적으로 출력부 부분을 문자열로 처리했으면 훨씬 간편했을거 같았습니다. 근데 문자열로 처리하려다보니 포인터를 많이 사용하더라구요. 그래서 든 생각이 C로 코딩테스트를 준비한다하면 포인터를 잘 사용할줄은 알아야 할까요?

김영우's profile image
김영우

asked

Ask a question