×

Adding one to the number represented an array of digits

You have given one array, which consists of values which represent the different digits of a number. You have to add 1 to this number and store the result in the same array. It is confirmed that in the array the digits are stored such that the most significant digit is the first element of the array.

Let’s take an example -

Input-  { 2, 3, 4 }

Output- { 2, 3, 5 }

Explanation- If we take number 2,3,4 in an array and add 1 to this number, we will get the result 2,3,5.

Algorithm:-

Step 1: Start

Step 2: An array is created of size n. Then values of the array are taken from the user.

Step 3: The values of array elements are taken from the user.

Step 4: A function is called to calculate the answer.

Step 5: In this function, we take the array.

Step 6: This function processes all the array elements by checking carry and sum and returns the calculated sum.

Step 7: The value of the answer is returned.

Step 8: The returned value will be printed.

Step 9: Stop.

Explanation of Algorithm: - Here, we will think about two things. The first one is the sum of two digits and the second one is carry. Let's understand the solution by an example. We are going to add one with the value 99. So, first, we will check from the last element of the array. We will add 1 with the number. If the sum is 10, the carry will be 1, and if less than 10, then the carry will be 0. We will traverse all the array elements and will add 1 if the carry is 1.

Code: -

Program in CPP
// program in CPP to add one to the number in array.
#include <bits/stdc++.h>
using namespace std;
void incrementVector(vector<int>& a)
{
	int n = a.size();
	a[n - 1] += 1;
	int carry = a[n - 1] / 10;
	a[n - 1] = a[n - 1] % 10;
	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 == 1)
		a.insert(a.begin(), 1);
}
int main()
{
	vector<int> vect{ 1, 7, 8, 9 };


	incrementVector(vect);


	for (int i = 0; i < vect.size(); i++)
		cout << vect[i] << " ";


	return 0;
}
Program in Java
// program in java to add one to the number in the array.
import java.io.*;
import java.util.*;
class jtp {
	static void incrementVector(Vector<Integer> a)
	{
		int n = a.size();
		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);
		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 == 1)
			a.add(0, 1);
	}
	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) + " ");
	}
}


Program in Python 
# Program in python to add one to the number in the array.
import math
def incrementVector(a):
	n = len(a)	
	a[n-1] += 1
	carry = a[n-1]/10
	a[n-1] = a[n-1] % 10
	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 == 1):
		a.insert(0, 1)
vect = [1, 7, 8, 9]
incrementVector(vect)
for i in range(0, len(vect)):
	print(vect[i], end=" ")
Program in JavaScript
// program in javascript to add one to the number in array.
<script>
const incrementVector = (a) =>
{
let n = a.length;
a[n - 1] += 1;
let carry = parseInt(a[n - 1] / 10);
a[n - 1] = a[n - 1] % 10;
for (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 == 1)
	a.unshift(1);
}
let vect = [ 1, 7, 8, 9 ];
incrementVector(vect);
for (let i = 0; i < vect.length; i++)
	document.write(`${vect[i]} `);
</script> 

Output:

[ 1, 7, 9, 0 ]

Complexity Analysis: -

Time complexity- Here, we need looping. For traversing the array, n time will be taken. So, we can find the solution within n time. Time complexity will be O(n).

Space complexity- Here, we need only constant memory. So, space complexity will be O(1).


Related Topics

Heap Sort in Data Structure

Heap Sort: Heap Sort is very useful and efficient sorting algorithm in data structure. We can say it is a comparison base sorting algorithm, similar sort where we will find...

2 minutes read.

What are the types of Trees in Data Structure

Data structures Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system used to store, manage,...

6 minutes read.

Recursion in Fibonacci

Fibonacci heap is considered to be a particular execution of the heap data structure that ultimately helps in making use of not just any number but the Fibonacci numbers. It...

3 minutes read.

What Is Graph Data Structure

A graph is generally a set of vertices and edges or border that is mainly used to join these vertices. A graph is basically pictured as a cyclic tree in...

7 minutes read.

Asymptotic Notation

Asymptotic notation is expressions that are used to represent the complexity of algorithms. The complexity of the algorithm is analyzed from two perspectives:  Time complexitySpace complexity Time complexity The time complexity of an algorithm is the...

3 minutes read.

Data Structures Algorithms

What is an Algorithm? An algorithm is a sequence of steps used to complete a job or get a desired result. It is similar to programming building elements that let cell...

4 minutes read.

Height of a binary tree

The height of a binary tree is generally defined as the height or length of the root _nod in the entire binary tree. In simple words, the height of a...

4 minutes read.

Threaded Binary Tree

The linked form of binary trees wastes storage capacity because more than half of the connection variables have a Missing value. A binary tree has several nodes. Hence n+1 link fields...

8 minutes read.

Assembly Line Scheduling

If we take an example of a car factory, there are two assembly lines. In an assembly line, we can assemble and repair the parts of a car. Now, suppose...

5 minutes read.

Convert Binary Tree into a Threaded Binary Tree

Implementation /*Writing a C++ program that will help us change the binary tree into a threaded binary tree and help us transform. */ #include <bits/stdc++.h> using namespace std; /*Creating the structure of a node...

11 minutes read.

Implementation of stack

Implementation of stack: The stack can be implemented in two ways: using array and using a linked list. The pop and push operations in the array are simpler than the...

3 minutes read.

Binary Tree Inorder Traversal

The binary tree is a type of tree in which each and every node has atleast two children except the leaf nodes. We have various operations in the binary tree,...

4 minutes read.

Merge Conflicts and ways to handle them

Merge Conflicts Whenever dealing with the Git merge operations, conflicts will be the frequently occurred. When more than two developers work on the same file on different systems using Git, they...

4 minutes read.

Binary search tree traversal in-order pre-order post-order examples

A binary search tree is a type of non-linear tree in which the tree contains at least two nods. It is called binary because of its nature that states bi...

8 minutes read.

Complete Binary tree

In this article, we will discuss the complete binary tree. But before start discussing the complete binary tree, we should first see a brief description of a binary tree. What is...

7 minutes read.

Red-black Tree in Data Structures?

A type of binary tree which is known as the Red-Black tree, is a specialized and unique tree. What is the urgency or, to be more precise, the necessity of...

10 minutes read.

Deletion Operation of the binary search tree in C++ language

A typical binary search tree implements some order to carry out the arrangements. As the name suggests, each parent node should have at most two children. The main rule in...

4 minutes read.

2-3 Trees and Basic Operations on them

2-3 Trees, like any other AVL trees or B-trees, are just a type of Height Balanced Tree. 2-3 Trees are the B-trees of order 3. Like every other B-tree, the...

4 minutes read.

Given Two Binary Trees, Check if it is Symmetric

Implementation // creating a C++ program that will help us check whether the two given trees are mirror images of each other.  #include<bits/stdc++.h> using namespace std; /* A given binary tree has a data...

5 minutes read.

DFS (Depth-first search) Algorithm: Data Structure

What is DFS (Depth-first search)? The depth first search is a graph traversal algorithm. The idea behind this algorithm is backtracking and it is a kind of recursive algorithm. In the...

3 minutes read.