How to Merge adjacent equal numbers? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to Merge adjacent equal numbers?

Hi , i wanna merge adjacent equal numbers. for example 1,3,3,5 gets to 1,9,5 or 2,2,2,8 gets to 8,8 I have given code "..." String merge (int [ ] ns, int i){ and I started with this int k , p; int[ ] ns = new int [intArr.length]; for ( k = i; k<= p; k++){ ns [k] = intArr[k]; } but i don't know how to continue or of its even right... could someone please help me ?:)

20th Nov 2016, 12:41 PM
thejokahr
thejokahr - avatar
5 Answers
+ 1
1,3,3,5 becomes 1,9,5 or 1,6,5? i think u mixed between intArr and ns in int[ ] ns = new int [intArr.length]; i imagine u meant int[ ] intArr = new int [ns.length]; its off the top of my head but in the for loop u can assign ns[k] to intArr[k] and if ns[k] = ns[k-1] u will sum intArr[k-1] = intArr[k-1] * ns[k] a few things u might wanna note 1) u will need different indexes for ns and intArr in the loop (maybe while loop will be better) - ns can keep going forward but if its a streak of the same number intArr wont move from its current index 2) intArr can end up in the same size or smaller than ns - but atm u are defining him as in the same size
20th Nov 2016, 1:11 PM
Ethan
Ethan - avatar
0
1,3,3 becomes 1,9 oh ok , thank you !! I will overthink and change it seems like a very dumb mistake made by me ..(I am new though)
20th Nov 2016, 1:18 PM
thejokahr
thejokahr - avatar
0
why does it become 1,9? do u multiply or sum? np btw :)
20th Nov 2016, 1:29 PM
Ethan
Ethan - avatar
0
multiple , like 2,2,2,7 gets 8,7 cause (2*2*2)
20th Nov 2016, 1:32 PM
thejokahr
thejokahr - avatar
0
good to know changed my first post from '+' to '*' ;)
20th Nov 2016, 1:33 PM
Ethan
Ethan - avatar