[programmers]level 1-2つの整数の和


👩🏻‍💻 質問する



👩🏻‍💻 正しいコード

class Solution {
  public long solution(int a, int b) {
      long answer = 0;
      if(a > b) {
          int t = a;
          a = b;
          b = t;
      }
      for(int i=a; i<=b; i++) {
          answer += i;
      }
      return answer;
  }
}
私はfor文で作ったのです...一番多い解気は等差数列と公式を書く解気です.

👩🏻‍💻 コードの改良

class Solution {
    public long solution(int a, int b) {
        return sumAtoB(Math.min(a, b), Math.max(b, a));
    }

    private long sumAtoB(long a, long b) {
        return (b - a + 1) * (a + b) / 2;
    }
}
だから持ってきた~等差数列と公式を関数sumatobの解に書く
また、ドアでなければ、Mathです.min(), Math.max()サイズで比較してsumatobのパラメータに渡した.