alorithm/programmers

[JAVA/프로그래머스] Lv1. 두 정수 사이의 합

Hannana. 2023. 4. 13. 23:47
반응형

[문제]

두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요.
예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다.

 

<제한 조건>

a와 b가 같은 경우는 둘 중 아무 수나 리턴하세요.
a와 b는 -10,000,000 이상 10,000,000 이하인 정수입니다.
a와 b의 대소관계는 정해져있지 않습니다.

 

<입출력 예>

a b return
3 5 12
3 3 3
5 3 12

 

 

 

[나의 풀이]

class Solution {
    public long solution(int a, int b) {
        long answer = 0;
        int max; int min;
        if(a>b){
            max = a;
            min=b;}
        else {
            max=b;
            min=a;}
        for(int i=min;i<=max;i++){
            answer += i;
        }

        return answer;
    }
    public static void main(String[] args){
        Solution r = new Solution();
    }
}

 

 

[다른 사람의 풀이 Ⅰ] - 등차수열의 합 공식 활용

class Solution {

    public long solution(int a, int b) {
        return sumAtoB(Math.min(a, b), Math.max(b, a));
    }

    private long sumAtoB(long a, long b) {
        return (b - a + 1) * (a + b) / 2;
    }
}

 

등차수열의 합 = 첫 항과 마지막 항을 더한 뒤 항의 개수를 곱하고 2로 나눈 값

(a1+an)/2 * n 

을 이용한 풀이다.

 

 

[다른 사람의 풀이 Ⅰ] - for문 단축

class Solution {
  public long solution(int a, int b) {
      long answer = 0;
      for (int i = ((a < b) ? a : b); i <= ((a < b) ? b : a); i++) 
          answer += i;

      return answer;
  }
}

 

 

 

 

비교식도 저만치 줄일 수 있구나

 

 

 

반응형