Problem solving/Algorithms

Sum between two integers (두 정수 사이의 합)

Young_A 2020. 8. 28. 03:40

목차

    Question

    When two integers a and b are given, return the sum of integers between a and b.

    For example, when a is 3 and b is 5, 3 + 4+ 5 = 12, then return 12.

     

    Limitation
    • If a and b are equal, return one of them.
    • a and b is more than or equal to -10,000,000 and less than or equal to 10,000,000.
    • a and b will be given regardless of size.

     

    Example of I/O
    a b return
    3 5 12
    3 3 3
    5 3 12

     

    My Solution
    def solution(a, b):
        answer = 0
        if a == b:
            answer = a
        elif a < b:
            for x in range(a, b + 1):
                answer += x
        else:
            for x in range(b, a + 1):
                answer += x
        return answer

     

    Explanation

     

    Reference

    프로그래머스 코딩테스트 연습 - 두 정수 사이의 합

     

    코딩테스트 연습 - 두 정수 사이의 합

    두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요. 예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다. 제한 조건 a와 b가 같은 경우

    programmers.co.kr