Home > Article > Backend Development > Add 1 to the number represented by the array (recursive method)
Given an array that is a collection of numbers represented by non-negative numbers, add 1 to the number (increment the number represented by the number). Numbers are stored in such a way that the highest digit is the first element of the array.
To add a number by 1 to the number represented by the number
Starting from the end of the array, addition means rounding the last number 4 to 5.
If the last element is 9, change it to 0 and carry = 1.
For the next iteration, check the carry and if it adds to 10, do the same as step 2.
After adding the carry, set the carry to 0 for the next iteration.
If vectors are added and the vector size is increased, append 1 at the beginning.
Suppose an array contains elements [7, 6, 3, 4], then the array represents the decimal number 1234, so adding 1 to this number will give 7635. So the new array will be [7, 6, 3, 5].
Input: [7, 6, 9, 9] Output: [7, 7, 0, 0] Input: [4, 1, 7, 8, 9] Output: [4, 1, 7, 9, 0]
Explanation Add 1 to the last element of the array if it is less than 9. If the element is 9, change it to 0 and recurse for the remaining elements of the array.
Explanation If the last element of the array is less than 9, add 1 to it. If the element is 9, change it to 0 and do a recursive operation on the remaining elements of the array.
#include <iostream> using namespace std; void sum(int arr[], int n) { int i = n; if(arr[i] < 9) { arr[i] = arr[i] + 1; return; } arr[i] = 0; i--; sum(arr, i); if(arr[0] > 0) { cout << arr[0] << ", "; } for(int i = 1; i <= n; i++) { cout << arr[i]; if(i < n) { cout << ", "; } } } int main() { int n = 4; int arr[] = {4, 1, 7, 8, 9}; sum(arr, n); return 0; }
The above is the detailed content of Add 1 to the number represented by the array (recursive method). For more information, please follow other related articles on the PHP Chinese website!