* 해답 아래 더보기에 Java 코드 기재 *
- 목차
- 음양 더하기
- 문제설명
- 제한사항
- 입출력 예
- 기본 상태
- 풀이에 필요한 조건
- 해답 +더보기
- 음양 더하기
음양 더하기
[문제 설명]
어떤 정수들이 있습니다. 이 정수들의 절댓값을 차례대로 담은 정수 배열 absolutes와 이 정수들의 부호를 차례대로 담은 불리언 배열 signs가 매개변수로 주어집니다. 실제 정수들의 합을 구하여 return 하도록 solution 함수를 완성해주세요.
[제한사항]
- absolutes의 길이는 1 이상 1,000 이하입니다.
- absolutes의 모든 수는 각각 1 이상 1,000 이하입니다.
- signs의 길이는 absolutes의 길이와 같습니다.
- signs[i] 가 참이면 absolutes[i] 의 실제 정수가 양수임을, 그렇지 않으면 음수임을 의미합니다.
[입출력 예 설명]
입출력 예
absolutes | signs | result |
[4,7,12] | [true,false,true] | 9 |
[1,2,3] | [false,false,true] | 0 |
입출력 예 #1
- signs가 [true,false,true] 이므로, 실제 수들의 값은 각각 4, -7, 12입니다.
- 따라서 세 수의 합인 9를 return 해야 합니다.
입출력 예 #2
- signs가 [false,false,true] 이므로, 실제 수들의 값은 각각 -1, -2, 3입니다.
- 따라서 세 수의 합인 0을 return 해야 합니다.
[기본 상태]
class Solution {
public int solution(int[] absolutes, boolean[] signs) {
int answer = 123456789;
return answer;
}
}
[풀이에 필요한 조건]
signs 배열과 absolutes 배열의 길이가 동일.
배열의 길이보다 작은 값까지 돌아가는 for 문을 작성.
for (int index = 0; index < signs.length; index++)
if(true)일 때, absolutes[index] 는 양수가 되고 결과값인 answer 에 + 해주면 된다.
if(false)일 때, absolutes[index] 는 음수가 되고 결과값인 answer 에 - 해주면 된다.
[해답]
class Solution {
public int solution(int[] absolutes, boolean[] signs) {
int answer = 0;
for (int index = 0; index < signs.length; index++) {
if (signs[index]) {
answer += absolutes[index];
} else {
answer -= absolutes[index];
}
}
return answer;
}
}
//해답
class Solution {
public int solution(int[] absolutes, boolean[] signs) {
int answer = 0;
for (int index = 0; index < signs.length; index++) {
if (signs[index]) {
answer += absolutes[index];
} else {
answer -= absolutes[index];
}
// index=0; signs[0] absolutes[0] answer=(+4)
// index=1; signs[1] absolutes[1] answer=(+4)+(-7)
// index=2; signs[2] absolutes[2] answer=(+4)+(-7)+(+12)
}
return answer;
}
}
//메인
public class Main {
public static void main(String[] args){
Solution sol = new Solution();
boolean signs1[] = {true,false,true};
int absolutes1[] = {4,7,12};
int addResult1 = sol.solution(absolutes1, signs1);
boolean signs2[] = {false,false,true};
int absolutes2[] = {1,2,3};
int addResult2 = sol.solution(absolutes2, signs2);
System.out.println(addResult1);
System.out.println(addResult2); }
}
추가
자료형의 명칭은 boolean(불린 또는 불리언이라고 부른다)이다.
참 또는 거짓의 값을 갖는 자료형을 부울 자료형이라고 한다.
부울 자료형에 대입되는 값은 참(true) 또는 거짓(false)만 가능하다.
ex)
int base = 180;
int height = 185;
boolean isTall = height > base;
if (isTall) {
System.out.println("키가 큽니다.");
}
1. int 형태의 변수 height, base를 비교하여 true 혹은 false 로 결과값을 isTall에 저장합니다.
2. 조건에 따라 값을 반환하도록 설정합니다. ( 위 경우 if ( height > base ) { } 와 결과값이 같습니다. )
'IT. Programming' 카테고리의 다른 글
Programmers. x만큼 간격이 있는 n개의 숫자 (0) | 2021.11.08 |
---|---|
TIL (0) | 2021.11.08 |
Programmers. 가운데 글자 가져오기 (0) | 2021.11.08 |
2주 1일차 알고리즘 문제풀이(개인) (0) | 2021.11.08 |
항해 99 1주차 (0) | 2021.11.07 |