Yesterday I had solved a string question. Today let’s do a lengthy question on arrays. Logic is as simple as a Grade 1 student but implementation and the edge case is where the beauty lies
Question link: https://leetcode.com/problems/add-to-array-form-of-integer/description/
We have to got back to pure basics for this. When we add any two digits and their sum is less than 10 then we just write it take the reamainder from division by 10 as carry. then we keep doing this till we run out of things to add or the carry is exhausted
Case1. n>m
simply initialize carry =0 and the keep updating it in each iteration. each step we keep res= sum of 2 digits then digit=res//10 and carry= res%10
But we need to add carry to the next final result also so we do a slight modification
we do res=sum+carry. as carry is 0 in the beginning it wont affect the first iteration and code will run smoothly.
Case2. n=m and carry remains
after we are finished with the digits we add the carry to the next remaining result array position
Let’s take up a test case and analyze
Test case: [11,12,2,3,4,5]
TASKs