프로그래머스 - LV1. 두 정수 사이의 합

김소정·2022년 3월 2일
0

프로그래머스

목록 보기
26/35

❔ 문제

❗ 내 풀이

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

🚩참고 (다른 풀이)


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


2.
class Solution {
  public long solution(int a, int b) {
      long answer = 0;
      if(a!=b){
          for(int i=Math.min(a,b);i<=Math.max(a,b);i++){	//Math 함수 사용해서도 가능
              answer+=i;
          }
      }else{
          answer=a;
      }
      return answer;
  }
}

📝 정리

💬 Math 함수 사용해서도 비교 가능!


profile
개발자 가보자고

0개의 댓글

관련 채용 정보