在用C ++表示为数字数组的数字上加一?

表示为数组的数字将数字的每个数字存储在数组的单个元素中。数组的长度等于数组中的位数,即对于四位数的数字,length = 3。数组的每个元素都是一个数字。数字的存储方式是,最后一个元素存储数字的最低有效位。并且第一个元素存储数字的最高有效位。例如,

数字-351932存储为{3,5,1,9,3,2}

要在此数字上加一个,需要在数组的最后一个元素上加一个,然后它们检查是否需要传播任何进位。如果最后一位的数字为9,则进位传播,最后一个元素的值变为0。

如果位被传播,则(n-1)位置的元素加1并检查进位传播。例如

将一个t0与{3,5,7,9}相加得出{3,5,8,0}。在这里,进位传播,值7增加到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