Given a nested list of integers, returns the sum of all integers in the list weighted by their depth
For example, given the list {{1,1},2,{1,1}} The function should return (four 1 's at depth 2, one 2 at depth 1)
Given the list {1,{4,{6}}} The function should return (one 1 at depth 1, one 4 at depth 2, one 6 at depth2)
/*** This was the interface that represents nested lists. * You should not implement it, or speculate on its implement ation. */ Public InterfaceNestedinteger {//Returns True if this nestedinteger holds a single integer, rather than a nested list Public BooleanIsinteger ();//Returns The single integer and the Nestedinteger holds, if it holds a single integer//Returns NULL if this nestedinteger holds a nested list PublicInteger Getinteger ();//Returns The nested list that this nestedinteger holds, if it holds a nested list//Returns NULL if this nestedinteger holds a single integer PublicList<nestedinteger>getList ();}
Public intSumofnestedinteger (Nestedinteger nest) {if(Nest.isinteger ()) {returnNest.getinteger (); } returnSumlist (Nest.getlist (), 1);}Private intSumlist (list<nestedinteger> List,intdepth) { intsum = 0; for(Nestedinteger item:list) {if(Item.isinteger ()) {sum+ = Item.getinteger () *depth; } Else{sum+ = Sumlist (Item.getlist (), depth+1); } } returnsum;}
Follow up:
Followup said change to return the sum of all integers in the list weighted by their "reversed depth".
That is, the result of {{1,1},2,{1,1}} is (1+1+1+1) *1+2*2=8
Ideas:
Requires two variable count, sum and prev
Example {{2,2,{3}},1,{2,2}}
Three floors altogether.
First layer prev = 1 sum=1
Second Layer prev =prev+2+2+2+2 last prev =9, sum = 10
Third layer prev =prev +3 prev = Sum =22
Theoretical results 3+2*2*4+1*3 =22
Prev Each time add itself, equivalent to the 1th number in the nth layer has been added n times, the 2nd number n-1 times, an analogy ...
Public intsumofreversedweight (Nestedinteger ni) {if(Ni.isinteger ()) {returnNi.getinteger (); } intprev = 0, sum = 0; List<NestedInteger> cur =ni.getlist (); List<NestedInteger> next =NewArraylist<>(); while(!Cur.isempty ()) { for(Nestedinteger item:cur) {if(Item.isinteger ()) {prev+=Item.getinteger (); } Else{Next.addall (item.getlist ()); } Sum+=prev; Cur=Next; Next=NewArraylist<>(); } } returnsum;}
The bull on the Mitbbs said:
To add all the numbers without permission * (n+1)
n is the deepest number
Then subtract the result of the original question.
This problem deliberately around people ....
Reference
http://www.careercup.com/question?id=5139875124740096
Http://www.mitbbs.com/article_t1/JobHunting/32850869_0_1.html
*sum of Nestedinteger