SECTION

https://www.codewars.com/kata/beginner-series-number-3-sum-of-numbers/train/java

 

Codewars: Train your coding skills

Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.

www.codewars.com

 

Instructions

 

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

Note: a and b are not ordered!

 

Examples

GetSum(1, 0) == 1 // 1 + 0 = 1
GetSum(1, 2) == 3 // 1 + 2 = 3
GetSum(0, 1) == 1 // 0 + 1 = 1
GetSum(1, 1) == 1 // 1 Since both are same
GetSum(-1, 0) == -1 // -1 + 0 = -1
GetSum(-1, 2) == 2 // -1 + 0 + 1 + 2 = 2

 

Solution

 public class Sum
  {
     public int GetSum(int smallnum, int bignum)
     {
      int sum = 0;
     
      if(bignum<smallnum) { return GetSum(bignum, smallnum); }
     
      else{
      
        // s = n/2(a+l)
        // s : sum 
        // a : firstnum 
        // l : lastnum
        // n : (l-a+1)
        
        sum = ((bignum-smallnum+1)*(smallnum+bignum)/2);
        
        return sum;
      }
     }
  }

 

profile

SECTION

@SectionR0

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그