This post is completed by 2 users
|
Add to List |
543. Adding One to a 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:
- Start by initializing a variable named "carry" with a value of 1. This variable will store the value to be added to the number initially.
- Iterate through the given array from right to left.
- For each element in the array, add the value of the carry to the element.
- After performing the addition, check if the resulting number is greater than or equal to 10.
- If the resulting number is indeed greater than or equal to 10, set carry = 1 and calculate the remainder of the addition using the modulo operator (%), giving us the new value for the element.
- If the resulting number is less than 10, set carry = 0 and keep the sum value as it is.
- Update the array with the new value obtained for the element at the corresponding index.
- Repeat steps 3 to 5 for the remaining elements in the array.
- Handle the edge case where the addition at index 0 results in a value greater than or equal to 10.
- If the addition at index 0 is indeed greater than or equal to 10, calculate the remainder of the addition using the modulo operator (%), obtaining the new value for the element. Create a new array with a size equal to the size of the given array plus 1.
- Store the value 1 at index 0 of the new array and copy all the elements from the processed array to the newly created array.
- Finally, return the resulting array.
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]