📜  向表示为数字数组的数字加一

📅  最后修改于: 2022-05-13 01:57:58.782000             🧑  作者: Mango

向表示为数字数组的数字加一

给定一个表示为数字数组的非负数,将数字加 1(增加数字表示的数字)。存储数字以使最高有效数字是数组的第一个元素。

例子 :

Input : [1, 2, 4]
Output : [1, 2, 5]

Input : [9, 9, 9]
Output : [1, 0, 0, 0]

方法:要将数字表示的数字加一,请按照以下步骤操作:

  • 就像我们在学校加法中所做的那样,从末尾解析给定的数组。
  • 如果最后一个元素是 9,则将其设为 0 并且进位 = 1。
  • 对于下一次迭代检查进位,如果它增加到 10,则与步骤 2 相同。
  • 添加进位后,使进位 = 0 进行下一次迭代。
  • 如果向量相加并增加向量大小,则在开头附加 1。

下面是对数字表示的数字加 1 的实现。

C++
// CPP implementation for Adding one
// to number represented by digits
#include 
using namespace std;
 
// function for adding one to number
void incrementVector(vector& 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 code
int main()
{
    vector vect{ 1, 7, 8, 9 };
 
    incrementVector(vect);
 
    for (int i = 0; i < vect.size(); i++)
        cout << vect[i] << " ";
 
    return 0;
}


Java
// Java implementation for Adding one
// to number represented by digits
import java.io.*;
import java.util.*;
 
class GFG {
 
    // function for adding one to number
    static void incrementVector(Vector 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 vect = new Vector();
        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#
// C# implementation for Adding one
// to number represented by digits
using 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] + " ");
    }
}
}


Python3
# 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 code
vect = [1, 7, 8, 9]
 
incrementVector(vect)
 
for i in range(0, len(vect)):
    print(vect[i], end=" ")
 
# This code is contributed by Gitanjali.


Javascript


C++
#include 
#include 
 
using namespace std;
 
void AddOne(vector& 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 code
int main()
{
    vector digits{ 1, 7, 8, 9 };
 
    AddOne(digits);
 
    for (int digit : digits)
        cout << digit << ' ';
 
    return 0;
}
// This code is contributed
// by Gatea David


Java
// Java implementation for Adding one
// to number represented by digits
import java.io.*;
import java.util.*;
class GFG {
 
  static void AddOne(Vector 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 digits = new Vector(Arrays.asList(1,7,8,9));
    AddOne(digits);
    for (int digit : digits)
      System.out.print(digit + " ");
  }
}
 
// This code is contributed by Shubham Singh


Python3
#Python Program
def 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#
// C# implementation for adding one
// to number represented by digits
using System;
using System.Xml;
 
     
class GFG{
 
// Driver code
static 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


Javascript


C++
// 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
using namespace std;
 
void plus_one(vector &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;i9 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 digits={9,8,9,9};
    int n=digits.size();
    plus_one(digits,n);
    for(int i=0;i


Java
// 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 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 digits = new Vector(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


Python3
# 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 code
digits = [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


C#
// 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


Javascript


输出
1 7 9 0 

另一种方法:从向量的末尾开始,如果最后一个元素是 9,则将其设置为 0,否则退出循环。

  • 如果循环将所有数字设置为 0(如果所有数字都是 9),则在开头插入 1。
  • 否则在循环停止的位置增加元素。
  • 不需要进位/除法/模数。

下面是实现:

C++

#include 
#include 
 
using namespace std;
 
void AddOne(vector& 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 code
int main()
{
    vector digits{ 1, 7, 8, 9 };
 
    AddOne(digits);
 
    for (int digit : digits)
        cout << digit << ' ';
 
    return 0;
}
// This code is contributed
// by Gatea David

Java

// Java implementation for Adding one
// to number represented by digits
import java.io.*;
import java.util.*;
class GFG {
 
  static void AddOne(Vector 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 digits = new Vector(Arrays.asList(1,7,8,9));
    AddOne(digits);
    for (int digit : digits)
      System.out.print(digit + " ");
  }
}
 
// This code is contributed by Shubham Singh

Python3

#Python Program
def 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#

// C# implementation for adding one
// to number represented by digits
using System;
using System.Xml;
 
     
class GFG{
 
// Driver code
static 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

Javascript


输出
1 7 9 0 

时间复杂度:O(n),其中 n 是位数。

辅助空间:O(1)

另一种方法:

在这种方法中,我们首先反转原始数组,然后我们使用一个进位变量来存储进位值。

现在我们从头开始迭代数组,我们只需添加 1 并进位到该数组在该索引处的值。在此之后,我们将检查该索引的值是否大于 9,然后我们可以将进位作为 10 的值,并且数组中该索引处的值将出现在其他地方的值,我们只需继续前进.

if digits[i]>9 then carry = digits[i]/10 and digits[i]%=10
if digits[i]<=9 then carry = 0.

我们继续这样做,直到到达数组的最后一个。现在出来之后,如果进位不为零,我们需要简单地将 1 也添加到数组中,然后再次反转数组,以便我们得到原始数组。

如何反转数组?

执行 :

C++

// 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
using namespace std;
 
void plus_one(vector &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;i9 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 digits={9,8,9,9};
    int n=digits.size();
    plus_one(digits,n);
    for(int i=0;i

Java

// 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 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 digits = new Vector(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

Python3

# 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 code
digits = [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

C#

// 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

Javascript


输出
9 9 0 0 

时间复杂度:O(n),其中 n 是数组的大小。

辅助空间:O(1)