Given a non-negative integer represented as an array arr[] without leading zeros, add 1 to the number and return the resulting array of digits. The most significant digit is stored at the starting index of the array.
Examples :
Input : [1, 2, 4]
Output : 125
Explanation: 124 + 1 = 125Input : [9, 9, 9]
Output: 1000
Explanation: 999 + 1 = 1000
Table of Content
[Naive Approach] Convert to Integer - O(n) Time and O(1) Space
Convert the array of digits into a number, add
1to it, and convert the result back into an array of digits.
- Traverse arr[] from left to right and construct the number by multiplying the current number by 10 and adding the current digit.
- Add 1 to the number.
- Extract the digits from the updated number and store them in an array.
- Reverse the array to restore the correct digit order and return it.
Note: This approach may cause integer overflow because the number can contain up to \(10^6\) digits, which exceeds the range of long long.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> addOne(vector<int>& arr) {
long long num = 0;
// Convert the array of digits into a number
for (int digit : arr) {
num = num * 10 + digit;
}
// Add 1 to the number
num++;
vector<int> res;
// Extract digits in reverse order
while (num > 0) {
res.push_back(num % 10);
num /= 10;
}
// Reverse the digits to get the correct order
reverse(res.begin(), res.end());
return res;
}
int main() {
vector<int> arr = {5, 6, 7, 8};
vector<int> res = addOne(arr);
cout << "[";
for (int i = 0; i < res.size(); i++) {
cout << res[i];
if (i < res.size() - 1) {
cout << ", ";
}
}
cout << "]";
return 0;
}
import java.util.ArrayList;
import java.util.Collections;
public class GFG {
public static ArrayList<Integer> addOne(int[] arr) {
long num = 0;
// Convert the array of digits into a number
for (int digit : arr) {
num = num * 10 + digit;
}
// Add 1 to the number
num++;
ArrayList<Integer> res = new ArrayList<>();
// Extract digits in reverse order
while (num > 0) {
res.add((int)(num % 10));
num /= 10;
}
// Reverse the digits to get the correct order
Collections.reverse(res);
return res;
}
public static void main(String[] args) {
int[] arr = {5, 6, 7, 8};
ArrayList<Integer> res = addOne(arr);
System.out.print("[");
for (int i = 0; i < res.size(); i++) {
System.out.print(res.get(i));
if (i < res.size() - 1) {
System.out.print(", ");
}
}
System.out.print("]");
}
}
def addOne(arr):
num = 0
# Convert the array of digits into a number
for digit in arr:
num = num * 10 + digit
# Add 1 to the number
num += 1
res = []
# Extract digits in reverse order
while num > 0:
res.append(num % 10)
num //= 10
# Reverse the digits to get the correct order
res.reverse()
return res
if __name__ == '__main__':
arr = [5, 6, 7, 8]
res = addOne(arr)
print('[', end='')
for i in range(len(res)):
print(res[i], end='')
if i < len(res) - 1:
print(', ', end='')
print(']')
using System;
using System.Collections.Generic;
public class GFG
{
public static List<int> addOne(int[] arr)
{
long num = 0;
// Convert the array of digits into a number
foreach (int digit in arr)
{
num = num * 10 + digit;
}
// Add 1 to the number
num++;
List<int> res = new List<int>();
// Extract digits in reverse order
while (num > 0)
{
res.Add((int)(num % 10));
num /= 10;
}
// Reverse the digits to get the correct order
res.Reverse();
return res;
}
public static void Main()
{
int[] arr = { 5, 6, 7, 8 };
List<int> res = addOne(arr);
Console.Write("[");
for (int i = 0; i < res.Count; i++)
{
Console.Write(res[i]);
if (i < res.Count - 1)
{
Console.Write(", ");
}
}
Console.Write("]");
}
}
function addOne(arr) {
let num = 0;
// Convert the array of digits into a number
for (let digit of arr) {
num = num * 10 + digit;
}
// Add 1 to the number
num++;
let res = [];
// Extract digits in reverse order
while (num > 0) {
res.push(num % 10);
num = Math.floor(num / 10);
}
// Reverse the digits to get the correct order
res.reverse();
return res;
}
// Driver code
let arr = [5, 6, 7, 8];
let res = addOne(arr);
console.log('[' + res.join(', ') + ']');
Output
[5, 6, 7, 9]
[Expected Approach - 1] Modular Arithmetic - O(n) Time and O(1) Space
The idea is to simulate the school addition method by traversing the digit array from the end and adding one to the number.
- If a digit becomes 10 after addition, it is set to 0 and a carry is propagated to the next digit.
- This process continues until there is no carry left or all digits have been processed.
- If a carry still remains after traversing the entire array, a new digit 1 is added at the beginning of the array.
#include <bits/stdc++.h>
using namespace std;
vector<int> addOne(vector<int> &arr) {
// Initialize carry to 1 because we need to add 1
int carry = 1;
// Traverse the array from right to left
for (int i = arr.size() - 1; i >= 0; i--) {
// Add the carry to the current digit
int sum = arr[i] + carry;
// Store the last digit of the sum
arr[i] = sum % 10;
// Calculate the carry for the next digit
carry = sum / 10;
}
// If a carry remains, insert it at the beginning
if (carry) {
arr.insert(arr.begin(), carry);
}
return arr;
}
int main() {
vector<int> arr = {9, 9, 9};
vector<int> res = addOne(arr);
cout << "[";
for (int i = 0; i < res.size(); i++) {
cout << res[i];
if (i < res.size() - 1) {
cout << ", ";
}
}
cout << "]";
return 0;
}
import java.util.ArrayList;
import java.util.Arrays;
public class GFG {
public static ArrayList<Integer> addOne(ArrayList<Integer> arr) {
// Initialize carry to 1 because we need to add 1
int carry = 1;
// Traverse the array from right to left
for (int i = arr.size() - 1; i >= 0; i--) {
// Add the carry to the current digit
int sum = arr.get(i) + carry;
// Store the last digit of the sum
arr.set(i, sum % 10);
// Calculate the carry for the next digit
carry = sum / 10;
}
// If a carry remains, insert it at the beginning
if (carry > 0) {
arr.add(0, carry);
}
return arr;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(9, 9, 9));
ArrayList<Integer> res = addOne(arr);
System.out.print("[");
for (int i = 0; i < res.size(); i++) {
System.out.print(res.get(i));
if (i < res.size() - 1) {
System.out.print(", ");
}
}
System.out.print("]");
}
}
def addOne(arr):
# Initialize carry to 1 because we need to add 1
carry = 1
# Traverse the array from right to left
for i in range(len(arr) - 1, -1, -1):
# Add the carry to the current digit
sum = arr[i] + carry
# Store the last digit of the sum
arr[i] = sum % 10
# Calculate the carry for the next digit
carry = sum // 10
# If a carry remains, insert it at the beginning
if carry:
arr.insert(0, carry)
return arr
if __name__ == '__main__':
arr = [9, 9, 9]
res = addOne(arr)
print('[', end='')
for i in range(len(res)):
print(res[i], end='' if i == len(res) - 1 else ', ')
print(']')
using System;
using System.Collections.Generic;
public class GFG {
public static List<int> addOne(int[] arr) {
// Initialize carry to 1 because we need to add 1
int carry = 1;
List<int> res = new List<int>(arr);
// Traverse the array from right to left
for (int i = res.Count - 1; i >= 0; i--) {
// Add the carry to the current digit
int sum = res[i] + carry;
// Store the last digit of the sum
res[i] = sum % 10;
// Calculate the carry for the next digit
carry = sum / 10;
}
// If a carry remains, insert it at the beginning
if (carry > 0) {
res.Insert(0, carry);
}
return res;
}
public static void Main() {
int[] arr = { 9, 9, 9 };
List<int> res = addOne(arr);
// Print the resulting array
Console.Write("[");
for (int i = 0; i < res.Count; i++) {
Console.Write(res[i]);
if (i < res.Count - 1) {
Console.Write(", ");
}
}
Console.Write("]");
}
}
function addOne(arr)
{
// Initialize carry to 1 because we need to add 1
let carry = 1;
// Traverse the array from right to left
for (let i = arr.length - 1; i >= 0; i--) {
// Add the carry to the current digit
let sum = arr[i] + carry;
// Store the last digit of the sum
arr[i] = sum % 10;
// Calculate the carry for the next digit
carry = Math.floor(sum / 10);
}
// If a carry remains, insert it at the beginning
if (carry > 0) {
arr.unshift(carry);
}
return arr;
}
// Driver code
let arr = [ 9, 9, 9 ];
let res = addOne(arr);
console.log("[" + res.join(", ") + "]");
Output
[1, 0, 0, 0]
[Expected Approach - 2] Check with 9 - O(n) Time and O(1) Space
Start from the last digit and add 1. Follow these steps to handle the carry:
- If the digit is less than 9, increase it by 1 and return the updated array.
- If the digit is 9, change it to 0 and add 1 to the digit on its left.
- If all digits are 9, change them to 0 and add 1 at the beginning of the array.
#include <bits/stdc++.h>
using namespace std;
vector<int> addOne(vector<int>& arr) {
int n = arr.size();
// Traverse from right to left
for (int i = n - 1; i >= 0; i--) {
// If the digit is less than 9, increment it
if (arr[i] < 9) {
arr[i]++;
return arr;
}
// If the digit is 9, change it to 0
arr[i] = 0;
}
// If all digits are 9, insert 1 at the beginning
arr.insert(arr.begin(), 1);
return arr;
}
int main() {
vector<int> arr = {9, 9, 9};
vector<int> res = addOne(arr);
cout << "[";
for (int i = 0; i < res.size(); i++) {
cout << res[i];
if (i < res.size() - 1)
cout << ", ";
}
cout << "]";
return 0;
}
import java.util.ArrayList;
class GFG {
static ArrayList<Integer> addOne(int[] arr) {
int n = arr.length;
// Traverse from right to left
for (int i = n - 1; i >= 0; i--) {
// If the digit is less than 9, increment it
if (arr[i] < 9) {
arr[i]++;
ArrayList<Integer> res = new ArrayList<>();
for (int digit : arr) {
res.add(digit);
}
return res;
}
// If the digit is 9, change it to 0
arr[i] = 0;
}
// If all digits are 9, insert 1 at the beginning
ArrayList<Integer> res = new ArrayList<>();
res.add(1);
for (int digit : arr) {
res.add(digit);
}
return res;
}
public static void main(String[] args) {
int[] arr = {9, 9, 9};
ArrayList<Integer> res = addOne(arr);
System.out.println(res);
}
}
def addOne(arr):
n = len(arr)
# Traverse from right to left
for i in range(n - 1, -1, -1):
# If the digit is less than 9, increment it
if arr[i] < 9:
arr[i] += 1
return arr
# If the digit is 9, change it to 0
arr[i] = 0
# If all digits are 9, insert 1 at the beginning
arr = [1] + arr
return arr
if __name__ == "__main__":
arr = [9, 9, 9]
res = addOne(arr)
print('[', end='')
for i in range(len(res)):
print(res[i], end='')
if i < len(res) - 1:
print(', ', end='')
print(']')
using System;
using System.Collections.Generic;
class GFG {
static List<int> addOne(int[] arr) {
int n = arr.Length;
// Traverse from right to left
for (int i = n - 1; i >= 0; i--) {
// If the digit is less than 9, increment it
if (arr[i] < 9) {
arr[i]++;
return new List<int>(arr);
}
// If the digit is 9, change it to 0
arr[i] = 0;
}
// If all digits are 9, insert 1 at the beginning
List<int> res = new List<int> { 1 };
res.AddRange(arr);
return res;
}
public static void Main() {
int[] arr = { 9, 9, 9 };
List<int> res = addOne(arr);
Console.WriteLine("[" + string.Join(", ", res) + "]");
}
}
function addOne(arr) {
let n = arr.length;
// Traverse from right to left
for (let i = n - 1; i >= 0; i--) {
// If the digit is less than 9, increment it
if (arr[i] < 9) {
arr[i]++;
return arr;
}
// If the digit is 9, change it to 0
arr[i] = 0;
}
// If all digits are 9, insert 1 at the beginning
let newArr = new Array(n + 1);
newArr[0] = 1;
for (let i = 0; i < n; i++) {
newArr[i + 1] = arr[i];
}
return newArr;
}
// Driver code
let arr = [9, 9, 9];
let res = addOne(arr);
console.log('[');
for (let i = 0; i < res.length; i++) {
process.stdout.write(res[i].toString());
if (i < res.length - 1)
process.stdout.write(', ');
}
console.log(']');
Output
[1, 0, 0, 0]
[Alternate Approach] Reverse the Array - O(n) Time and O(1) Space
Reverse arr[] so that the least significant digit comes first. This allows adding 1 from the beginning and handling the carry easily.
- Reverse the array to process digits from right to left.
- If the current digit is less than 9, increase it by 1 and stop.
- If the digit is 9, change it to 0 and continue to the next digit.
- If all digits are 9, append 1 to the reversed array.
- Reverse the array again to restore the original digit order.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> addOne(vector<int>& arr) {
int n = arr.size();
// Reverse the array
reverse(arr.begin(), arr.end());
// Add 1 and handle carry
int i = 0;
while (i < n && arr[i] == 9) {
arr[i] = 0;
i++;
}
if (i < n) {
arr[i]++;
} else {
// If all digits are 9, add an extra digit
arr.push_back(1);
}
// Restore the original digit order
reverse(arr.begin(), arr.end());
return arr;
}
int main() {
vector<int> arr = {9, 9, 9};
vector<int> res = addOne(arr);
cout << "[";
for (int i = 0; i < res.size(); i++) {
cout << res[i];
if (i < res.size() - 1) {
cout << ", ";
}
}
cout << "]";
return 0;
}
import java.util.ArrayList;
class GFG {
static ArrayList<Integer> addOne(int[] arr) {
int n = arr.length;
// Reverse the array
reverse(arr);
// Add 1 and handle carry
int i = 0;
while (i < n && arr[i] == 9) {
arr[i] = 0;
i++;
}
ArrayList<Integer> res = new ArrayList<>();
// If all digits are 9, add 1 as the extra digit
if (i == n) {
res.add(1);
} else {
arr[i]++;
}
// Add the digits in reverse order
for (int digit : arr) {
res.add(digit);
}
// Reverse the result to restore the original order
reverse(res);
return res;
}
static void reverse(int[] arr) {
int left = 0, right = arr.length - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
static void reverse(ArrayList<Integer> arr) {
int left = 0, right = arr.size() - 1;
while (left < right) {
int temp = arr.get(left);
arr.set(left, arr.get(right));
arr.set(right, temp);
left++;
right--;
}
}
public static void main(String[] args) {
int[] arr = {9, 9, 9};
ArrayList<Integer> res = addOne(arr);
for (int digit : res) {
System.out.print(digit + " ");
}
}
}
def addOne(arr):
n = len(arr)
# Reverse the array
arr = arr[::-1]
# Add 1 and handle carry
i = 0
while i < n and arr[i] == 9:
arr[i] = 0
i += 1
if i < n:
arr[i] += 1
else:
# If all digits are 9, add an extra digit
arr.append(1)
# Restore the original digit order
arr = arr[::-1]
return arr
if __name__ == '__main__':
arr = [9, 9, 9]
res = addOne(arr)
print('[', end='')
for i in range(len(res)):
print(res[i], end='')
if i < len(res) - 1:
print(', ', end='')
print(']')
using System;
using System.Collections.Generic;
class GFG {
static List<int> addOne(int[] arr) {
Array.Reverse(arr);
int n = arr.Length;
// Add 1 and handle carry
for (int i = 0; i < n; i++) {
if (arr[i] < 9) {
arr[i]++;
break;
}
arr[i] = 0;
}
// If all digits were 9, append 1
if (arr[n - 1] == 0) {
bool allZero = true;
foreach (int digit in arr) {
if (digit != 0) {
allZero = false;
break;
}
}
if (allZero) {
Array.Resize(ref arr, n + 1);
arr[n] = 1;
}
}
// Restore the original digit order
Array.Reverse(arr);
return new List<int>(arr);
}
public static void Main() {
int[] arr = { 9, 9, 9 };
List<int> res = addOne(arr);
Console.WriteLine("[" + string.Join(", ", res) + "]");
}
}
function addOne(arr) {
let n = arr.length;
// Reverse the array
arr.reverse();
// Add 1 and handle carry
let i = 0;
while (i < n && arr[i] === 9) {
arr[i] = 0;
i++;
}
if (i < n) {
arr[i]++;
} else {
// If all digits are 9, add an extra digit
arr.push(1);
}
// Restore the original digit order
arr.reverse();
return arr;
}
// Driver code
let arr = [9, 9, 9];
let res = addOne(arr);
console.log('[' + res.join(', ') + ']');
Output
1000