Java Varargs - Simple Addition

Sort by

recency

|

310 Discussions

|

  • + 0 comments

    java15:

    import java.io.; import java.lang.reflect.; import java.util.*;

    class Add { public void add(int... numbers) { int sum = 0; StringBuilder sb = new StringBuilder(); for (int i = 0; i < numbers.length; i++) { sum += numbers[i]; sb.append(numbers[i]); if (i != numbers.length - 1) { sb.append("+"); } } sb.append("=").append(sum); System.out.println(sb); } }

    public class Solution { public static void main(String[] args) { try { Scanner sc = new Scanner(System.in); int n1 = sc.nextInt(); int n2 = sc.nextInt(); int n3 = sc.nextInt(); int n4 = sc.nextInt(); int n5 = sc.nextInt(); int n6 = sc.nextInt(); 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);

            // Reflection check (required by HackerRank)
            Method[] methods = Add.class.getDeclaredMethods();
            Set<String> set = new HashSet<>();
            boolean overload = false;
            for (Method method : methods) {
                if (set.contains(method.getName())) {
                    overload = true;
                    break;
                }
                set.add(method.getName());
            }
            if (overload) {
                throw new Exception("Overloading not allowed");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    }

  • + 0 comments
    class Add {
        void add(int a, int b, int... other) {
            String sumStr = String.format("%d+%d", a, b);
            int sum = a+b;
            
            for (int i=0; i<other.length; i++) {
                sumStr += String.format("+%d", other[i]);
                sum += other[i];
            }
            
            System.out.println(sumStr + "=" + sum);
        }
    }
    
  • + 0 comments
    class Add {
        public void add(int... n) {
            int sum = 0;
            List<String> arr = new ArrayList<>();
            for (int num : n) {
                sum += num;
                arr.add(Integer.toString(num));
            }
            
            System.out.println(String.join("+", arr) + "=" + sum);
        }
    }
    
  • + 0 comments

    class Add{

    void add(int... a){
        int sum=0;
     for(int i=0;i<a.length;i++){
        sum=sum+a[i];
        System.out.print(a[i]);
        if(i<(a.length-1)){
          System.out.print("+");  
        }
     } 
     System.out.println("="+sum);
    }
    

    }

  • + 0 comments

    Here is Java Varargs - Simple Addition solution - https://programmingoneonone.com/hackerrank-java-varargs-simple-addition-solution.html