• Source
    1. /* package whatever; // don't place package name! */
    2.  
    3. import java.util.*;
    4. import java.lang.*;
    5. import java.io.*;
    6.  
    7. /**
    8.  * Given a nested list of integers, returns the sum of all integers in the list weighted by their depth
    9.  * For example, given the list {{1,1},2,{1,1}} the function should return 10 (four 1's at depth 2, one 2 at depth 1)
    10.  * Given the list {1,{4,{6}}} the function should return 27 (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3)
    11.  */
    12. class Ideone
    13. {
    14. public static void main(String[] args) {
    15.  
    16. // {{1,1},2,{1,1}}
    17. List<Object> parent1 = new ArrayList<Object>();
    18.  
    19. List<Object> child1 = new ArrayList<Object>();
    20. child1.add(1);
    21. child1.add(1);
    22. parent1.add(child1);
    23.  
    24. parent1.add(2);
    25.  
    26. List<Object> child3 = new ArrayList<Object>();
    27. child3.add(1);
    28. child3.add(1);
    29. parent1.add(child3);
    30.  
    31. System.out.println(getSum(parent1, 1));
    32.  
    33. // {1,{4,{6}}}
    34. List<Object> parent2 = new ArrayList<Object>();
    35. parent2.add(1);
    36.  
    37. List<Object> child11 = new ArrayList<Object>();
    38. child11.add(4);
    39.  
    40. List<Object> child111 = new ArrayList<Object>();
    41. child111.add(6);
    42.  
    43. child11.add(child111);
    44. parent2.add(child11);
    45. System.out.println(getSum(parent2, 1));
    46. }
    47.  
    48. private static int getSum(Object list, int depth){
    49. if(list == null) return 0;
    50.  
    51. int sum = 0;
    52. if(list.getClass() == ArrayList.class){
    53. for(Object nestedList:(ArrayList<Object>)list){
    54. if(nestedList.getClass() == ArrayList.class){
    55. sum += getSum(nestedList, depth+1);
    56. }else{
    57. sum += getSum(nestedList, depth);
    58. }
    59. }
    60. }else{
    61. sum += (Integer)list *depth;
    62. System.out.println("CurrentSum => " + sum + " integer => " + list + " Depth => " + depth);
    63. }
    64. return sum;
    65. }
    66.  
    67. /**
    68.  * This is the interface that allows for creating nested lists. You should not implement it, or speculate about its implementation
    69.  */
    70. public interface NestedInteger
    71. {
    72. // Returns true if this NestedInteger holds a single integer, rather than a nested list
    73. public boolean isInteger();
    74.  
    75. // Returns the single integer that this NestedInteger holds, if it holds a single integer
    76. // Returns null if this NestedInteger holds a nested list
    77. public Integer getInteger();
    78.  
    79. // Returns the nested list that this NestedInteger holds, if it holds a nested list
    80. // Returns null if this NestedInteger holds a single integer
    81. public List<NestedInteger> getList();
    82. }
    83. }
    84.