Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Add 1 to the number represented as array (Recursive Approach)?
Given an array which is a collection of non-negative numbers represented as an array of digits, add 1 to the number (increment the number represented by the digits). The digits are stored such that the most significant digit is the first element of the array.
To add 1 to the number represented by digits −
- Start from the rightmost digit (last element of the array)
- If the last digit is less than 9, simply add 1 to it
- If the last digit is 9, make it 0 and carry 1 to the next position
- Continue this process recursively for all digits
- If all digits are 9, the array size increases and we prepend 1
For example, if an array contains elements [7, 6, 3, 4], it represents decimal number 7634. Adding 1 results in 7635, so the new array becomes [7, 6, 3, 5].
Syntax
void addOne(int arr[], int index);
Examples
Input: [7, 6, 9, 9] Output: [7, 7, 0, 0] Input: [4, 1, 7, 8, 9] Output: [4, 1, 7, 9, 0]
Example: Recursive Implementation
This approach uses recursion to handle the carry operation from right to left −
#include <stdio.h>
void addOne(int arr[], int index) {
if (index < 0) {
return;
}
if (arr[index] < 9) {
arr[index] = arr[index] + 1;
return;
}
arr[index] = 0;
addOne(arr, index - 1);
}
void printArray(int arr[], int n) {
printf("[");
for (int i = 0; i < n; i++) {
printf("%d", arr[i]);
if (i < n - 1) {
printf(", ");
}
}
printf("]
");
}
int main() {
int arr1[] = {7, 6, 3, 4};
int n1 = 4;
printf("Original: ");
printArray(arr1, n1);
addOne(arr1, n1 - 1);
printf("After adding 1: ");
printArray(arr1, n1);
int arr2[] = {7, 6, 9, 9};
int n2 = 4;
printf("\nOriginal: ");
printArray(arr2, n2);
addOne(arr2, n2 - 1);
printf("After adding 1: ");
printArray(arr2, n2);
return 0;
}
Original: [7, 6, 3, 4] After adding 1: [7, 6, 3, 5] Original: [7, 6, 9, 9] After adding 1: [7, 7, 0, 0]
How It Works
- Base Case: If index is negative, stop recursion
- Simple Case: If current digit is less than 9, add 1 and return
- Carry Case: If current digit is 9, make it 0 and recurse to the previous index
- The recursion naturally handles the carry propagation from right to left
Key Points
- Time complexity is O(n) in worst case when all digits are 9
- Space complexity is O(n) due to recursive call stack
- This approach modifies the original array in place
- For cases where all digits are 9 (like [9,9,9]), additional logic is needed to handle array expansion
Conclusion
The recursive approach provides a clean solution for adding 1 to a number represented as an array. It elegantly handles carry propagation through recursive calls, making the code intuitive and easy to understand.
