×

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

Graph Data Structure

A graph is a non-primitive and non-linear data structure. It is a group of (V, E) where V is a set of vertexes, and E is a set of edge....

3 minutes read.

Difference Between Linear and Non Linear Data Structures

Data Structure A data structure is a data object together with the relationships between the instances and the individual elements that compose an instance. These relationships are defined by the operations...

5 minutes read.

Collision Resolution Techniques

Collision Resolution Techniques Collision in hashing In this, the hash function is used to compute the index of the array.The hash value is used to store the key in the hash table,...

2 minutes read.

Treap data structure

In this article, we will discuss the treap data structure. The word treap is a combination of 'tree' and 'heap'. So, treap data structure is a combination of a heap...

8 minutes read.

Rearrange a linked list into alternate fashion first and the last element

Rearrange a linked list into alternate fashion first and the last element This article will explain how to rearrange the linked list into alternate fashion first and the last element. Here,...

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.

Trim a binary search tree

Implementation //writing a C++ program will help us eliminate the keys that are out of the league.  #include<bits/stdc++.h> using namespace std; //we are now creating a binary search tree node consisting of key left...

8 minutes read.

Rotate a Singly Linked List

Rotate a Singly Linked List This article will explain how we can rotate the singly linked list. Here we have given a singly linked list, and we need to rotate this...

4 minutes read.

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

3 minutes read.

Binary Tree Uses

A binary tree is a tree data structure containing hubs with at most two children for instance a right and left child. The node at the top is insinuated as the...

3 minutes read.

Convert binary tree to a doubly linked list

Implementation //creating a C++ program for the transition of a binary tree into a linked list. #include <iostream> using namespace std; /* Firstly, let’s create a binary tree that will help us in setting...

4 minutes read.

Recursion - Factorial and Fibonacci

In this article, we will learn how to find the factorial of a number and the Fibonacci series up to n using the recursion method. What is recursion? Defining anything in terms...

7 minutes read.

Array vs Linked List: Data Structure

Data structure: Difference Between Array and Linked List What is Array? An array is a linear data structure that can store similar data items for further processing. The similar data items...

3 minutes read.

Binary Tree in Data Structures

What is a Binary Tree in Data Structures? The term binary itself means bi, which implies two of anything. So very clearly, we know we present the trees in the form...

6 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.

Serialize and Deserialize a Binary Tree

Implementation // Writing a C++ program to check the serialization and deserialization of binary tree.   #include <iosstream> /* A binary tree node contains a key and a pointer to the left and right...

4 minutes read.

Array Data Structure

Data Structure Array: The array is a non-primitive and linear data structure that is a group of similar data items. That is, it can store only one type of data....

6 minutes read.

Bitonical Sort

Arranging an unordered collecttion of things into asignificant order. •Comparision Based Model: Bubble Sort, Selection Sort -->Non-Comparison Based. Model: Bucket Sort or on the other hand a Count Sort Bitonic Sort: Bitonic sort Algorithm was made...

5 minutes read.

Lowest Common Ancestor in a Binary Tree

The lowest node in the tree that contains both n1 and n2 as descendants is the lowest common ancestor (LCA), and n1 and n2 are the nodes for which we...

11 minutes read.

Difference between Structured and Object-Oriented Analysis

Analysis means observing and collecting relevant information about the structure of something or the basic details of a system's requirements. Structured and Object Oriented Analysis are both widely used in...

2 minutes read.