Adding one to number represented as array of digits - GeeksforGeeks

05 Jan, 2022
Given a non-negative number represented as an array of digits, add 1 to the number ( increment the number represented by the digits ). The digits are stored such that the most significant digit is the first element of the array.
Examples : 
Input : [1, 2, 4]
Output : [1, 2, 5]

Input : [9, 9, 9]
Output : [1, 0, 0, 0]
Approach: To add one to the number represented by digits, follow the below steps : 
Parse the given array from the end as we do in school addition.
If the last elements are 9, make it 0 and carry = 1.
For the next iteration check carry and if it adds to 10, do same as step 2.
After adding carry, make carry = 0 for the next iteration.
If the vectors add and increase the vector size, append 1 in the beginning.
Below is the implementation to add 1 to number represented by digits. 
C++
Java
C#
Python3
Javascript
// CPP implementation for Adding one// to number represented by digits#include <bits/stdc++.h>using namespace std; // function for adding one to numbervoid incrementVector(vector<int>& a){    int n = a.size();     // Add 1 to last digit and find carry    a[n - 1] += 1;    int carry = a[n - 1] / 10;    a[n - 1] = a[n - 1] % 10;     // Traverse from second last digit    for (int i = n - 2; i >= 0; i--) {        if (carry == 1) {            a[i] += 1;            carry = a[i] / 10;            a[i] = a[i] % 10;        }    }     // If carry is 1, we need to add    // a 1 at the beginning of vector    if (carry == 1)        a.insert(a.begin(), 1);} // driver codeint main(){    vector<int> vect{ 1, 7, 8, 9 };     incrementVector(vect);     for (int i = 0; i < vect.size(); i++)        cout << vect[i] << " ";     return 0;}
// Java implementation for Adding one// to number represented by digitsimport java.io.*;import java.util.*; class GFG {     // function for adding one to number    static void incrementVector(Vector<Integer> a)    {        int n = a.size();         // Add 1 to last digit and find carry        a.set(n - 1, a.get(n - 1) + 1);        int carry = a.get(n - 1) / 10;        a.set(n - 1, a.get(n - 1) % 10);         // Traverse from second last digit        for (int i = n - 2; i >= 0; i--) {            if (carry == 1) {                a.set(i, a.get(i) + 1);                carry = a.get(i) / 10;                a.set(i, a.get(i) % 10);            }        }         // If carry is 1, we need to add        // a 1 at the beginning of vector        if (carry == 1)            a.add(0, 1);    }     // Driver code    public static void main(String[] args)    {        Vector<Integer> vect = new Vector<Integer>();        vect.add(1);        vect.add(7);        vect.add(8);        vect.add(9);         incrementVector(vect);         for (int i = 0; i < vect.size(); i++)            System.out.print(vect.get(i) + " ");    }} // This code is contributed by Gitanjali.
// C# implementation for Adding one// to number represented by digitsusing System;using System.Xml; namespace myTry {class Program {    // Driver code    static void Main(string[] args)    {        int carry = 0;        int[] array = new int[] { 1, 7, 8, 9 };         // find the length of the array        int n = array.Length;         // Add 1 to the last digit and find carry        array[n - 1] += 1;        carry = array[n - 1] / 10;        array[n - 1] = array[n - 1] % 10;         // Traverse from second last digit        for (int i = n - 2; i >= 0; i--) {            if (carry == 1) {                array[i] += 1;                carry = array[i] / 10;                array[i] = array[i] % 10;            }        }         // If the carry is 1, we need to add        // a 1 at the beginning of the array        if (carry == 1) {            Array.Resize(ref array, n + 1);            array[0] = carry;        }         for (int i = 0; i < array.Length; i++)            Console.WriteLine(array[i] + " ");    }}}
# Python implementation for Adding one# to number represented by digits import math # function for adding one to number  def incrementVector(a):     n = len(a)     # Add 1 to last digit and find carry    a[n-1] += 1    carry = a[n-1]/10    a[n-1] = a[n-1] % 10     # Traverse from second last digit    for i in range(n-2, -1, -1):        if (carry == 1):            a[i] += 1            carry = a[i]/10            a[i] = a[i] % 10     # If carry is 1, we need to add    # a 1 at the beginning of vector    if (carry == 1):        a.insert(0, 1)  # driver codevect = [1, 7, 8, 9] incrementVector(vect) for i in range(0, len(vect)):    print(vect[i], end=" ") # This code is contributed by Gitanjali.
<script>// JavaScript implementation for Adding one// to number represented by digits // function for adding one to numberconst incrementVector = (a) =>{let n = a.length; // Add 1 to last digit and find carrya[n - 1] += 1;let carry = parseInt(a[n - 1] / 10);a[n - 1] = a[n - 1] % 10; // Traverse from second last digitfor (let i = n - 2; i >= 0; i--) {    if (carry == 1) {        a[i] += 1;        carry = parseInt(a[i] / 10);        a[i] = a[i] % 10;    }} // If carry is 1, we need to add// a 1 at the beginning of vectorif (carry == 1)    a.unshift(1);} // driver code let vect = [ 1, 7, 8, 9 ]; incrementVector(vect); for (let i = 0; i < vect.length; i++)    document.write(`${vect[i]} `); // This code is contributed by rakeshsahni </script>
1 7 9 0 
Another Approach: Start from the end of the vector and if the last element is 9 set it to 0, else exit the loop.
If the loop setted all digits to 0 (if all digits were 9) insert 1 at the beginning.
Else increment the element at the position where the loop stopped.
No carry/division/modulo is needed.
Below is the implementation:
C++
Java
Python3
C#
Javascript
#include <iostream>#include <vector> using namespace std; void AddOne(vector<int>& digits){    // initialize an index (digit of units)    int index = digits.size() - 1;     // while the index is valid and the value at [index] ==    // 9 set it as 0    while (index >= 0 && digits[index] == 9)        digits[index--] = 0;     // if index < 0 (if all digits were 9)    if (index < 0)        // insert an one at the beginning of the vector        digits.insert(digits.begin(), 1, 1);     // else increment the value at [index]    else        digits[index]++;} // Driver codeint main(){    vector<int> digits{ 1, 7, 8, 9 };     AddOne(digits);     for (int digit : digits)        cout << digit << ' ';     return 0;}// This code is contributed// by Gatea David
// Java implementation for Adding one// to number represented by digitsimport java.io.*;import java.util.*;class GFG {   static void AddOne(Vector<Integer> digits)  {      // initialize an index (digit of units)    int index= digits.size() - 1;     // while the index is valid and the value at [index] ==    // 9 set it as 0    while (index >= 0 && digits.get(index) == 9){      digits.set(index, 0);      index -= 1;    }     // if index < 0 (if all digits were 9)    if (index < 0)      // insert an one at the beginning of the vector      digits.set(0, 1);     // else increment the value at [index]    else      digits.set(index, digits.get(index) + 1);   }   // Driver code  public static void main(String[] args)  {    Vector<Integer> digits = new Vector<Integer>(Arrays.asList(1,7,8,9));    AddOne(digits);    for (int digit : digits)      System.out.print(digit + " ");  }} // This code is contributed by Shubham Singh
#Python Programdef AddOne(digits):       # initialize an index (digit of units)    index = len(digits) - 1         # while the index is valid and the value at [index] ==    # 9 set it as 0    while (index >= 0 and digits[index] == 9):        digits[index] = 0        index -= 1             # if index < 0 (if all digits were 9)    if (index < 0):               # insert an one at the beginning of the vector        digits.insert(0, 1)             # else increment the value at [index]    else:        digits[index]+=1  digits = [1, 7, 8, 9] AddOne(digits) for digit in digits:    print(digit, end =' ')     # This code is contributed# by Shubham Singh
// C# implementation for adding one// to number represented by digitsusing System;using System.Xml;      class GFG{ // Driver codestatic void Main(string[] args){    int[] digits = new int[] { 1, 7, 8, 9 };     // Initialize an index (digit of units)    int index = digits.Length - 1;             // While the index is valid and the value at        // [index] == 9 set it as 0        while (index >= 0 && digits[index] == 9)            digits[index--] = 0;             // If index < 0 (if all digits were 9)        if (index < 0)        {                         // Insert an one at the beginning of the vector            Array.Resize(ref digits, index + 1);            digits[0] = 1;        }                // Else increment the value at [index]        else            digits[index]++;     foreach(int digit in digits)        Console.Write(digit + " ");}} // This code is contributed by Shubham Singh
<script>// JavaScript implementation for Adding one// to number represented by digits // function for adding one to numberconst AddOne = (digits) =>{     // initialize an index (digit of units)    let index = digits.length -1;     // while the index is valid and the value at [index] ==    // 9 set it as 0    while (index >= 0 && digits[index] == 9)        digits[index--] = 0;     // if index < 0 (if all digits were 9)    if (index < 0)        // insert an one at the beginning of the vector        digits.insert(digits.begin(), 1, 1);     // else increment the value at [index]    else        digits[index]++;}// driver code let digits = [ 1, 7, 8, 9 ]; AddOne(digits); for (let i = 0; i < digits.length; i++)    document.write(`${digits[i]} `); // This code is contributed by Shubham Singh </script>
1 7 9 0 
Time Complexity: O(n), where n is the number of digits.
Auxiliary Space: O(1)
Another Approach : 
In this approach we first reverse the original array then we take a carry variable to store the carry value.
Now we start iterating over the array from the start and we simply add 1 and carry to the value of that array at that index. After this we are going to check if that the value of that index is it greater than 9 then we can take carry as the ten’s value and the value at that index in the array will the value present at the ones place else we simply move on.
if digits[i]>9 then carry = digits[i]/10 and digits[i]%=10
if digits[i]<=9 then carry = 0.
We keep on doing this until we reach the last of the array. Now after coming out also if carry is not zero the we need to simply add that 1 the array also and then again reverse the array so that we get our original array.
How to Reverse an Array ?
Implementation :
C++
Java
Python3
C#
Javascript
// This Code represents one more approach to// Add 1 to the number repesentes in the array.// This code is contributed by Omkar Subhash Ghongade.#include<bits/stdc++.h>using namespace std; void plus_one(vector<int> &digits,int n){    // We are reversing the original arr    // So thar we need to iterate from Back.    reverse(digits.begin(),digits.end());    // Taking a carry variable in case if there is any carry    int carry=0;    for(int i=0;i<n;i++)    {        // Intitally carry is 0 so this is base case        if(i==0)            digits[i]+=(1+carry);        // If carry is not equal to zero it should be added to        // array element at that position.        else if(carry!=0)            digits[i]+=carry;        // Now to get carry, i.e.        // If digits[i]>9 we get the value at tens place in carry        // or else if digits[i]<9 carry will be 0        carry=digits[i]/10;        // Now if carry is not equal to 0        // so at that index we should keep the value present        // at the ones place so we di digits[i]%10        if(carry!=0)            digits[i]=digits[i]%10;    }    // Afte doing all that if carry is still there which means    // one more element is needed to be added to the array    if(carry!=0)        digits.push_back(carry);    // Now we reverse the array so that we get the final array    reverse(digits.begin(),digits.end());} int main(){    vector<int> digits={9,8,9,9};    int n=digits.size();    plus_one(digits,n);    for(int i=0;i<digits.size();i++)    {        cout<<digits[i]<<" ";    }}
// This Code represents one more approach to// Add 1 to the number repesentes in the array.// This code is contributed by Omkar Subhash Ghongade.import java.io.*;import java.util.*;class GFG {   public static void plus_one(Vector<Integer> digits,int n)  {     // We are reversing the original arr    // So thar we need to iterate from Back.    Collections.reverse(digits);     // Taking a carry variable in case if there is any carry    int carry = 0;    for(int i = 0; i < n; i++)    {       // Intitally carry is 0 so this is base case      if(i == 0)        digits.set(i, digits.get(i) + 1 + carry);       // If carry is not equal to zero it should be added to      // array element at that position.      else if(carry != 0)        digits.set(i, digits.get(i) + carry);       // Now to get carry, i.e.      // If digits[i]>9 we get the value at tens place in carry      // or else if digits[i]<9 carry will be 0      carry = digits.get(i) / 10;       // Now if carry is not equal to 0      // so at that index we should keep the value present      // at the ones place so we di digits[i]%10      if(carry != 0)        digits.set(i, digits.get(i) % 10);    }     // Afte doing all that if carry is still there which means    // one more element is needed to be added to the array    if(carry != 0)      digits.set(digits.size() - 1, carry);     // Now we reverse the array so that we get the final array    Collections.reverse(digits);  }   public static void main (String[] args)  {    Vector<Integer> digits = new Vector<Integer>(Arrays.asList(9,8,9,9));    int n = digits.size();    plus_one(digits, n);    for(int i = 0; i < n; i++)    {      System.out.print(digits.get(i) + " ");    }  }} // This code is contributed by Shubham Singh
# This Code represents one more approach to# Add 1 to the number repesentes in the array.def plus_one(digits, n):       # We are reversing the original arr    # So thar we need to iterate from Back.    digits.reverse()         # Taking a carry variable in case if there is any carry    carry = 0         for i in range(n):                 # itally carry is 0 so this is base case        if(i == 0):            digits[i] += (1 + carry)                 # If carry is not equal to zero it should be added to        # array element at that position.        elif(carry != 0):            digits[i] += carry                     # Now to get carry, i.e.        # If digits[i]>9 we get the value at tens place in carry        # or else if digits[i]<9 carry will be 0        carry = digits[i]//10                 # Now if carry is not equal to 0        # so at that index we should keep the value present        # at the ones place so we di digits[i]%10        if(carry != 0):            digits[i] = digits[i] % 10                 # Afte doing all that if carry is still there which means    # one more element is needed to be added to the array    if(carry != 0):        digits.append(carry)             # Now we reverse the array so that we get the final array    digits.reverse() # Diver codedigits = [9, 8, 9, 9]n = len(digits)plus_one(digits, n) for i in digits:    print(i, end =" ")     # This code is contributed# by Shubham Singh
// This Code represents one more approach to// Add 1 to the number repesentes in the array. using System; public class GFG{   public static void Main ()  {    int[] digits = new int[] {9,8,9,9};    int n = digits.Length;         // We are reversing the original arr    // So thar we need to iterate from Back.    Array.Reverse(digits);     // Taking a carry variable in case if there is any carry    int carry = 0;    for(int i = 0; i < n; i++)    {       // Intitally carry is 0 so this is base case      if(i == 0)        digits[i] = digits[i] + 1 + carry;       // If carry is not equal to zero it should be added to      // array element at that position.      else if(carry != 0)        digits[i] = digits[i] + carry;       // Now to get carry, i.e.      // If digits[i]>9 we get the value at tens place in carry      // or else if digits[i]<9 carry will be 0      carry = digits[i] / 10;       // Now if carry is not equal to 0      // so at that index we should keep the value present      // at the ones place so we di digits[i]%10      if(carry != 0)        digits[i] = digits[i]%10;    }     // Afte doing all that if carry is still there which means    // one more element is needed to be added to the array    if(carry != 0)      digits[digits.Length -1] = carry;     // Now we reverse the array so that we get the final array    Array.Reverse(digits);         for(int i = 0; i < n; i++)    {      Console.Write(digits[i] + " ");    }       }} // This code is contributed by Shubham Singh
<script>// This Code represents one more approach to// Add 1 to the number repesentes in the array. var digits = [9,8,9,9];var n = digits.length; // We are reversing the original arr// So thar we need to iterate from Back.digits.reverse(); // Taking a carry variable in case if there is any carryvar carry = 0;for(var i = 0; i < n; i++){    // Intitally carry is 0 so this is base case    if(i == 0)        digits[i] = digits[i] + 1 + carry;    // If carry is not equal to zero it should be added to    // array element at that position.    else if(carry != 0)        digits[i] = digits[i] + carry;            // Now to get carry, i.e.    // If digits[i]>9 we get the value at tens place in carry    // or else if digits[i]<9 carry will be 0    carry = parseInt(digits[i] / 10);         // Now if carry is not equal to 0    // so at that index we should keep the value present    // at the ones place so we di digits[i]%10    if(carry != 0)        digits[i] = digits[i]%10;} // Afte doing all that if carry is still there which means// one more element is needed to be added to the arrayif(carry != 0)    digits[digits.length -1] = carry; // Now we reverse the array so that we get the final arraydigits.reverse(); for(var i = 0; i < n; i++){    document.write(digits[i] + " ");}  // This code is contributed by Shubham Singh</script>
9 9 0 0 
Time Complexity : O(n), where n is the size of the array.
Auxiliary Space : O(1)
PINKYWALIA
davidgatea21
rexomkar
rakeshsahni
varshagumber28
SHUBHAMSINGH10
cpp-vector
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in C++
C++ Classes and Objects
Interfaces in Java
Operator Overloading in C++
Copy Constructor in C++
C++ Data Types
Overriding in Java
Types of Operating Systems
Polymorphism in C++
Python program to check if a string is palindrome or not