코딩테스트/프로그래머스

[Lv.1] 음양 더하기

민톨이 2024. 8. 8. 22:47
728x90

📋 문제

어떤 정수들이 있습니다. 이 정수들의 절댓값을 차례대로 담은 정수 배열 absolutes와 이 정수들의 부호를 차례대로 담은 불리언 배열 signs가 매개변수로 주어집니다. 실제 정수들의 합을 구하여 return 하도록 solution 함수를 완성해주세요.

 

📋 입출력 예시

 

📋 풀이

class Solution {
    public int solution(int[] absolutes, boolean[] signs) {
        int answer = 0;
        for(int i=0;i<absolutes.length;i++){
            if(signs[i]){
             answer += absolutes[i];
            } else {
              answer -=  absolutes[i];
            }
        }
        return answer;
    }
    
    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] absolutes = {4, 7, 12};
        boolean[] signs = {true, false, true};
        System.out.println(sol.solution(absolutes, signs));  // 결과는 9
    }


}

어렵다어려워,,, 참고하지 않으면 풀 수 없ㄴㅔ ㅣ싀익ㅜ

 

for 루프: absolutes 배열을 순회하면서 해당 인덱스의 signs[i] 값에 따라 더하거나 빼는 방식으로 값을 계산

  • if : signs[i]가 true이면 absolutes[i]를 answer에 더함
  • else : signs[i]가 false이면 absolutes[i]를 answer에서 뺌

'코딩테스트 > 프로그래머스' 카테고리의 다른 글

[Lv.0] 각도기  (0) 2024.08.11
[Lv.0] 로그인 성공?  (0) 2024.08.11
[Lv.1]2021카카오 : 숫자 문자열과 영단어  (0) 2024.08.08
[Lv.0] 1로 만들기  (0) 2024.08.08
[Lv.0]카운트 다운  (0) 2024.08.08