This post is completed by 2 users

  • 1
Add to List
Medium

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:
  1. 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.
  2. Iterate through the given array from right to left.
  3. For each element in the array, add the value of the carry to the element.
  4. 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.
  5. Update the array with the new value obtained for the element at the corresponding index.
  6. Repeat steps 3 to 5 for the remaining elements in the array.
  7. 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.
  8. Finally, return the resulting array.
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]