This post is completed by 2 users
|
Add to List |
Plus one to number represented by an array
Objective: Given a number represented by an array. You need to add one to that number and return the array.
Example:num [] = [2, 2, 2] output: [2, 2, 3] num[] = [3, 6, 9] output : [3, 7, 0] num[] = [9, 6, 9] output: [9, 7, 0] num[] = [9, 9, 9] output: [1, 0, 0, 0]Solution:
Let's take a variable carry = 1 (because we need to add 1 to number to start with) and iterate the given array from right to left and for current element add the carry and after addition IF number is greater than 10 then do carry =1 and addition = addition MOD 10 ELSE do carry =0 and put the addition back to the same index in array. Likewise do it for the rest of the indexes. Edge case to handle is if addition at index 0 is greater than 10, in that case do addition = addition MOD 10 and create a new array of size = size of given array + 1. Now store 1 at index 0 and copy all the elements from the given processed array to the newly created array. See the code below for more understanding.
Code:
Output:
Input: [2, 2, 2], add one and Output is: [2, 2, 3] Input: [3, 6, 9], add one and Output is: [3, 7, 0] Input: [9, 6, 9], add one and Output is: [9, 7, 0] Input: [9, 9, 9], add one and Output is: [1, 0, 0, 0]
Also Read: