본문 바로가기
코테연습

13.Sum of Numbers

by hxunz 2022. 3. 22.

Description:

Given two integers a and b, which can be positive or negative, find the sum of all the integers between and including them and return it. If the two numbers are equal return a or b.

Note: a and b are not ordered!

Examples (a, b) --> output (explanation)

(1, 0) --> 1 (1 + 0 = 1)
(1, 2) --> 3 (1 + 2 = 3)
(0, 1) --> 1 (0 + 1 = 1)
(1, 1) --> 1 (1 since both are same)
(-1, 0) --> -1 (-1 + 0 = -1)
(-1, 2) --> 2 (-1 + 0 + 1 + 2 = 2)

 

function getSum( a,b )
{
  let num = 0;
  if (a <= b) {
    for(i = a; i <= b; i++) {
      num += i;
    }
    return num;
  } else {
    for(i = b; i <= a; i++) {
      num += i;
    }
    return num;
  }
}

num을 0이라고 선언해두고 a가 b보다 작거나 같을때 a부터 b까지 숫자 하나하나씩 더해서 num에 저장하고 리턴하도록 했다.

a가 b보다 클때는 b부터 a까지 숫자 하나씩 더해서 num에 저장하고 리턴하도록 했다. 

'코테연습' 카테고리의 다른 글

15.Two to One  (0) 2022.03.24
14.Sum of two lowest positive integers  (0) 2022.03.24
12.Credit Card Mask  (0) 2022.03.21
11.Complementary DNA  (0) 2022.03.20
10.Jaden Casing Strings  (0) 2022.03.20

댓글