- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

A number represented as array stored each digit of the number in a single element of the array. The length of the array is equal to the number of digits in the array i.e. length = 3 for four digit number. Each element of the array is a single digit number. The number is stored in such a way that the last element store the least significant digit of the number. And the first element stores the most significant digit of the number. For example,

Number − 351932 is stored as {3,5,1,9,3,2}

To add one to this number need you to add one to the last element of the array and them check if any carry needs to be propagated or not. If the number at the last bit is 9 then a carry is propagated and last element’s value becomes 0.

If bit is propagated then, the element at (n-1) position is incremented by one and carry propagation is checked. For example

Adding one t0 {3,5,7,9} gives {3,5,8,0}. Here, a carry is propagated and value of seven is increased to 8.

#include <bits/stdc++.h> using namespace std; void addone(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> num{2, 3, 9, 9}; cout<<"The original number is : "; for (int i = 0; i < num.size(); i++) cout << num[i]; cout<<endl; addone(num); cout<<"The incremented value is : "; for (int i = 0; i < num.size(); i++) cout << num[i]; return 0; }

The original number is 2399 The incremented value is 2400

- Related Questions & Answers
- Adding one to number represented as array of digits in C Program?
- Sum of two numbers where one number is represented as array of digits in C++
- Add 1 to number represented as array (Recursive Approach)?
- Add 1 to the number represented as array (Recursive Approach)?
- Divide large number represented as string in C++ Program
- Recursively adding digits of a number in JavaScript
- Add 1 to a number represented as linked list?
- Add 1 to a number represented as a linked list?
- Multiply Large Numbers represented as Strings in C++
- Adding digits of a number using more than 2 methods JavaScript
- Convert number to reversed array of digits JavaScript
- Check if a number can be represented as sum of non zero powers of 2 in C++
- Check if a number can be represented as a sum of 2 triangular numbers in C++
- Evaluate a boolean expression represented as string in C++
- Convert to number with digits as 3 and 8 only in C++

Advertisements