[Programmers / JAVA] Level 1 Sum Between Two Integers (12912)
[Programmers / JAVA] Level 1 Sum Between Two Integers (12912)
Given two integers a and b, complete a function, solution, that returns the sum of all integers between a and b, inclusive. For example, if a = 3 and b = 5, then 3 + 4 + 5 = 12, so it returns 12.
@RWBwritten at 2021-12-16 11:31:27
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
Given two integers a and b, complete a function, solution, that returns the sum of all integers between a and b, inclusive. For example, if a = 3 and b = 5, then 3 + 4 + 5 = 12, so it returns 12.
- If a and b are equal, return either one.
- a and b are integers between -10,000,000 and 10,000,000, inclusive.
- There is no guarantee about the relative magnitude of a and b.
| a | b | return |
|---|---|---|
| 3 | 5 | 12 |
| 3 | 3 | 3 |
| 5 | 3 | 12 |
Simply loop with a for statement between a and b, adding up every number in between.
Here, to construct the for loop, we need to determine the relative magnitude of a and b.
Since the response is long, be careful not to return it as int.
JAVA
/** * Sum Between Two Integers class * * @author RWB * @since 2021.12.13 Mon 14:16:50 */ class Solution { /** * Method that returns the answer * * @param a: [int] integer 1 * @param b: [int] integer 2 * * @return [long] the answer */ public long solution(int a, int b) { long answer = 0; int start = Math.min(a, b); int end = Math.max(a, b); for (int i = start; i <= end; i++) { answer += i; } return answer; } }
# Programmers# Algorithm# JAVA# Level 1
