inblog logo
|
stupefyee
    알고리즘문제풀기

    [JAVA 문제 풀이] 90. 연속된 수의 합

    프로그래머스 (120923)
    Stupefyee's avatar
    Stupefyee
    Feb 18, 2025
    [JAVA 문제 풀이] 90. 연속된 수의 합
    Contents
    내가 작성한 코드다른 사람의 코드
    school.programmers.co.kr
    https://school.programmers.co.kr/learn/courses/30/lessons/120923
    notion image
     

    내가 작성한 코드

    • 배열의 합에 집중함
      • class Solution { public int[] solution(int num, int total) { int[] answer = new int[num]; // 정답 배열 초기화 for(int i = 1; i <= num; i++) { answer[i-1] = i; } while (true) { int sum = Arrays.stream(answer).sum(); // 배열의 합 // 배열의 합이 total보다 작을때 배열의 모든 원소값을 1씩 증가 if (sum < total) { for(int i = 0; i < answer.length; i++) { answer[i]++; } continue; } // 배열의 합이 total보다 클때 배열의 모든 원소값을 1씩 감소 if (sum > total) { for(int i = 0; i < answer.length; i++) { answer[i]--; } continue; } return answer; } } }
         

    다른 사람의 코드

    • 시작하는 숫자를 구하는 것이 관건
      • class Solution { public int[] solution(int num, int total) { int[] answer = new int[num]; int check = num * (num + 1) / 2; // num개의 연속된 정수의 합 int start = (total - check) / num + 1; // 시작 숫자 계산 for (int i = 0; i < answer.length; i++) { answer[i] = start + i; // 연속된 숫자 배열 생성 } return answer; } }
    Share article
    Contents
    내가 작성한 코드다른 사람의 코드

    stupefyee

    RSS·Powered by Inblog