[프로그래머스]연속된 수의 합

allnight5·2022년 12월 22일
0

프로그래머스 입문

목록 보기
52/53

연속된 세 개의 정수를 더해 12가 되는 경우는 3, 4, 5입니다. 두 정수 num과 total이 주어집니다. 연속된 수 num개를 더한 값이 total이 될 때, 정수 배열을 오름차순으로 담아 return하도록 solution함수를 완성해보세요.

파이썬 첫번째

자바 두번째 성공

class Solution {
    public int[] solution(int num, int total) {
        int[] answer = new int[num];
        int start = 1;
        int end = num+start;
        int total_sum; 
        int now;
        while (true) {
            now = 0;
            total_sum =0; // 첫번째 실패시 초기화를 안시켜줘서 계속돌아감
            for(int i = start; i<end;i++){
                total_sum += i;
                answer[now] = i;
                now += 1;
            }
             
            if (total_sum == total)
                break;

            else if (total_sum > total){
                start -= 1;
                end -= 1;
            }

            else if (total_sum < total ){
                start += 1;
                end += 1; 
            }
        }
        return answer;
    }
    
}

자바 계산식

class Solution {
    public int[] solution(int num, int total) {
        int[] answer = new int[num];
        int temp = 0;
        for(int i=0;i<num;i++){
            temp+=i;
        }
        int value = (total-temp)/num;
        System.out.println(temp + ": value :"+value);
        for(int i=0;i<num;i++){
            answer[i]=i+value;
        }

        return answer;
    }
}
profile
공부기록하기

0개의 댓글