Adding one to number represented as array of digits in C++?

C++Server Side ProgrammingProgramming

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.

Example

 Live Demo

#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;
}

Output

The original number is 2399
The incremented value is 2400
raja
Published on 03-Oct-2019 12:46:07
Advertisements