題目描述

您需要建立一個Add類別,並撰寫方法來完成數字的加總。



原題網址

https://www.hackerrank.com/challenges/simple-addition-varargs

輸入格式

有六行輸入,每行都是一個整數。

輸出格式

只會有四行輸出。要計算輸入的整數加總。

範例輸入

1
2
3
4
5
6

範例輸出

1+2=3
1+2+3=6
1+2+3+4+5=15
1+2+3+4+5+6=21

解題概念

利用Java的Varargs(可變長參數),讓方法能夠支援任意數量的參數輸入,再將輸入的參數用加法算式表現出來。

參考答案

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

class Add {

    public void add(final int... n) throws Exception {
        final int length_dec = n.length - 1;
        int sum = 0;
        for (int i = 0; i <= length_dec; ++i) {
            final int v = n[i];
            sum += v;
            System.out.print(v);
            if (i < length_dec) {
                System.out.print("+");
            }
        }
        System.out.println("=".concat(String.valueOf(sum)));
    }
}

public class Solution {

    public static void main(final String[] args) {
        try {
            final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            final int n1 = Integer.parseInt(br.readLine());
            final int n2 = Integer.parseInt(br.readLine());
            final int n3 = Integer.parseInt(br.readLine());
            final int n4 = Integer.parseInt(br.readLine());
            final int n5 = Integer.parseInt(br.readLine());
            final int n6 = Integer.parseInt(br.readLine());
            final Add ob = new Add();
            ob.add(n1, n2);
            ob.add(n1, n2, n3);
            ob.add(n1, n2, n3, n4, n5);
            ob.add(n1, n2, n3, n4, n5, n6);
            final Method[] methods = Add.class.getDeclaredMethods();
            final Set<String> set = new HashSet<>();
            boolean overload = false;
            for (int i = 0; i < methods.length; i++) {
                if (set.contains(methods[i].getName())) {
                    overload = true;
                    break;
                }
                set.add(methods[i].getName());

            }
            if (overload) {
                throw new Exception("Overloading not allowed");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}