Coding Test/[프로그래머스] Java

[프로그래머스 / Java] Lv.1 두 정수 사이의 합

annovation 2025. 4. 30. 12:20

Question

https://school.programmers.co.kr/learn/courses/30/lessons/12912

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


Code

💡방법 1

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;
    }
}
  • Math.max() [각주:1]
    • 두 숫자 중 최대값 반환
  • Math.min() [각주:2]
    • 두 숫자 중 최소값 반환

💡방법 2

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;
  }
}