[Programmers / JAVA] Level 1 Adding Positives and Negatives (76501)
[Programmers / JAVA] Level 1 Adding Positives and Negatives (76501)
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
🔗 Adding Positives and Negatives
There are some integers. You're given an integer array absolutes containing the absolute values of these integers in order, and a boolean array signs containing the signs of these integers in order, as parameters. Complete the solution function so that it computes and returns the sum of the actual integers.
- The length of absolutes is between 1 and 1,000 inclusive.
- Every number in absolutes is between 1 and 1,000 inclusive.
- The length of signs is equal to the length of absolutes.
- If signs[i] is true, it means the actual integer value of absolutes[i] is positive; otherwise, it's negative.
| absolutes | signs | result |
|---|---|---|
| { 4, 7, 12 } | { true, false, true } | 9 |
| { 1, 2, 3 } | { false, false, true } | 0 |
Input/Output Example #1
Since signs is { true, false, true }, the actual values are 4, -7, and 12 respectively.
Therefore, it should return the sum of the three numbers, 9.
Input/Output Example #2
Since signs is { false, false, true }, the actual values are -1, -2, and 3 respectively.
Therefore, it should return the sum of the three numbers, 0.
absolutes holds the absolute value of each number, and signs holds the sign of each number. We just need to look up each element by index and add or subtract absolutes based on the value of signs.
Since absolutes and signs are the same size, it doesn't matter which array's index we use.
JAVA
for (int i = 0; i < absolutes.length; i++) { answer += (signs[i] ? absolutes[i] : -absolutes[i]); }
Based on the value of signs[i], add or subtract absolutes[i] and accumulate it into answer.
JAVA
/** * Adding Positives and Negatives class * * @author RWB * @since 2021.12.10 Fri 00:09:32 */ class Solution { /** * Method that returns the answer * * @param absolutes: [int[]] Array of absolute values * @param signs: [boolean[]] Signs of the integers * * @return [int] The answer */ public int solution(int[] absolutes, boolean[] signs) { int answer = 0; for (int i = 0; i < absolutes.length; i++) { answer += (signs[i] ? absolutes[i] : -absolutes[i]); } return answer; } }
