코드로 우주평화

Sum of Numbers 본문

나는 이렇게 학습한다/Algorithm & SQL

Sum of Numbers

daco2020 2022. 3. 3. 22:54
반응형

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)

 

 

 

Solution:

1. Sort the low and high numbers.
2. Returns the sum of all numbers between two numbers.

 

 

JS code ::

function getSum(a, b){

  // Sort ascending
  let arr = [a, b].sort(function(a, b){return a - b}) 
  let answer = 0
  
  // Find the range
  for (let i = arr[0]; i < arr[1]+1; i++){ 
    answer += i
  }
  return answer
}

 

 

 

Python code ::

def get_sum(a,b):
    a, b = min(a,b), max(a,b)
    return sum([ i for i in range(a,b+1)])

 

 

 

반응형

'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글

Equal Sides Of An Array  (0) 2022.03.05
Is this a triangle?  (0) 2022.03.04
Grasshopper - Summation  (0) 2022.03.03
Counting Duplicates  (0) 2022.03.01
Growth of a Population  (0) 2022.03.01