Home > Backend Development > C++ > body text

Add 1 to the number represented by the array (recursive method)

王林
Release: 2023-08-28 17:17:06
forward
1697 people have browsed it

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

Example

Input: [7, 6, 9, 9]
Output: [7, 7, 0, 0]
Input: [4, 1, 7, 8, 9]
Output: [4, 1, 7, 9, 0]
Copy after login

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.

Example

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.

Example

#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;
}
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!