Development/CodeWorkout

[CodeWorkout] X323: sumRange

bbubbush 2022. 5. 6. 00:10

Question

Given two integers low and high representing a range, return the sum of the integers in that range. For example, if low is 12 and high is 18, the returned values should be the sum of 12, 13, 14, 15, 16, 17, and 18, which is 105. If low is greater than high, return 0.

 

Examples:

sumRange(12, 18) -> 105

sumRange(1, 5) -> 15

sumRange(1, 100) -> 5050

 

Answer

반응형
package com.bbubbush.tistory;

public class X323 {
  public static void main(String[] args) {
    int low = 0;
    int high = 0;
    low = 12;
    high = 18;
    System.out.printf("[low = %d, high = %d]\n", low, high);
    System.out.println(sumRange(low, high));

    low = 10;
    high = 108;
    System.out.printf("[low = %d, high = %d]\n", low, high);
    System.out.println(sumRange(low, high));
  }

  public static int sumRange(int low, int high) {
    if (low > high) {
      return 0;
    }
    long sumOfHigh = high * (high + 1) / 2L;
    long sumOfLow = low * (low + 1) / 2L;
    return (int) (sumOfHigh - sumOfLow + low);
  }
}

 

Ref

https://github.com/bbubbush/codeworkout/blob/master/src/com/bbubbush/tistory/X323.java

 

GitHub - bbubbush/codeworkout

Contribute to bbubbush/codeworkout development by creating an account on GitHub.

github.com

 

'Development > CodeWorkout' 카테고리의 다른 글

[CodeWorkout] X158: bunnyEars2  (0) 2022.05.05
[CodeWorkout] X119: squareUp  (0) 2022.04.27
[CodeWorkout] X121: extraEnd  (0) 2022.04.26
[CodeWorkout] X125: repeatSeparator  (0) 2022.04.25