first code: https://ide.codingblocks.com/s/653466
second code(modified): https://ide.codingblocks.com/s/653462
first code is working fine only if single digit numbers are present in both the arrays but if more than one digit numbers are present I tried to modify the code which is the second code. But this is giving TLE error. Please check and correct it once and add a comment also wherever I have done wrong.
First code passing 2 test cases and second is giving TLE error
hi @sb1251224_6919c19fccd96630
For the given sample case , arr1=[1, 0, 2, 9] and arr2=[3, 4, 5, 6, 7] .Each element of both the arrays is a digit .Thus, both array forms two separate numbers and we need to calculate the sum of these two numbers.
Take an ans array (whose size is equal to the (max size of the two arrays +1 )) which will store the final number formed.
Start adding both the numbers digit by digit from the end i.e. 9+7=16 thus 6 is stored in the ans array at last index (as we are updating our array from last) and 1 is taken as carry.Thus, this process is repeated for every digit and at the end if carry is not 0 it is stored at the starting index of the ans array.First digit of the ans array represent carry over which is zero in this case. So ans is [3, 5, 5, 9, 6].
Algorithm:
1.Traverse both the arrays simultaneously from the end until we reach the 0th index of either of the array.
2.While traversing each element of array, add an element from both arrays and carry from the previous sum.
…………2.1 Store the unit digit of the sum(obtained by doing - sum%10) in the ans array.
…………2.2 forward carry(obtained by doing - sum/10) for the next index sum.
3.After the loop ends we are left with one of the arrays and the carry.
4.We will now repeat step 2 but now for one array which is left after the loop.
5.If carry !=0 then store the carry in the 0th index of ans array.
6.Print the ans array .
refer this code -->
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.