본문 바로가기

ALGORITHM

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

 

코딩테스트 연습 - 두 정수 사이의 합

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

programmers.co.kr

⏱소요 시간 - 10분

 

🔑해결 방법

 

아주 아주 쉬운 문제였다.

if문으로 분기해서 풀어보고, 중복된 코드를 줄이기 위해 max, min을 먼저 정해놓는 두 가지 풀이로 풀어보았다.

 

Math.max(a,b) : a와 b 중에 큰 수를 리턴

Math.min(a,b) : a와 b 중에 작은 수를 리턴

 

 

🔎소스 코드

 

package step1;

// 두 정수 사이의 합
public class Ex12 {

	public static void main(String[] args) {
		
		System.out.println(solution(3, 5));
		System.out.println(solution(3, 3));
		System.out.println(solution(5, 3));
		System.out.println(solution(2, -1));
		
	}
	
	public static long solution(int a, int b) {
		
		long answer = 0;
		
		int max = Math.max(a, b);
		int min = Math.min(a, b);
		
		for(int i = min; i <= max; i++) { // i <= max 이므로 a, b가 같을 경우도 포함
			answer += i;
		}
		
		return answer;
		
	}

}

 

package step1;

// 두 정수 사이의 합
public class Ex12_1 {

	public static void main(String[] args) {
		
		System.out.println(solution(3, 5));
		System.out.println(solution(3, 3));
		System.out.println(solution(5, 3));
		System.out.println(solution(2, -1));
		
	}
	
	public static long solution(int a, int b) {
		
		long answer = 0;
		
		if(a < b) {
			for(int i = a; i <= b; i++) {
				answer = answer + i;
			}
		} else if(a > b) {
			for(int i = a; i >= b; i--) {
				answer = answer + i;
			}
		} else {
			return a;
		}
		
		return answer;
		
	}

}