blog.itcode.devblog.itcode.dev

[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.

[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.
RWB0104
@RWBwritten at 2021-12-16 11:31:27
Programmers

시리즈 모아보기

Programmers

39 / 78
RankLanguage Used
Level 1

🖼️ JAVA

🔗 Sum Between Two Integers

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.
abreturn
3512
333
5312

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
ship
blog.itcode.dev

Notes from the π-th Alpaca

7.0.1
Developed by RWB since 2021.057th upgraded at 2026.08