Practice › Arrays
Plus One
Easy · Arrays · Asked at Google, Amazon, TCS, Infosys
A large non-negative number is given as its digits, most significant first. Add one to it and print the digits of the result.
Input
First line: n (number of digits). Second line: n digits separated by spaces (no leading zero unless the number is 0).
Output
The digits of the number plus one, separated by spaces.
Constraints
- 1 ≤ n ≤ 10^5
- 0 ≤ digit ≤ 9
Walk from the last digit: a 9 becomes 0 and the carry moves left; any other digit just increases by one and you stop. If every digit was 9, put a 1 in front.
Example 1
Input
3 1 2 3
Output
1 2 4
Example 2
Input
2 9 9
Output
1 0 0
Hints
- Adding one only changes the trailing 9s and the digit just before them.
- If every digit is 9, the answer is 1 followed by n zeros.
Approach
Start from the last digit. While the digit is 9, set it to 0 and move left (the carry continues). The first digit that is not 9 just increases by one and the carry stops. If you run off the front, every digit was 9 — print a 1 before the zeros. The number can have 10^5 digits, so never convert it to an integer type.
Complexity: O(n) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> d(n);
for (auto &x : d) cin >> x;
int i = n - 1;
while (i >= 0 && d[i] == 9) d[i--] = 0;
if (i < 0) d.insert(d.begin(), 1);
else d[i]++;
for (size_t k = 0; k < d.size(); k++) cout << d[k] << (k + 1 < d.size() ? ' ' : '\n');
return 0;
}Python solution
import sys
data = sys.stdin.read().split()
n = int(data[0])
d = list(map(int, data[1 : 1 + n]))
i = n - 1
while i >= 0 and d[i] == 9:
d[i] = 0
i -= 1
if i < 0:
d.insert(0, 1)
else:
d[i] += 1
print(" ".join(map(str, d)))Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
int[] d = new int[n];
for (int k = 0; k < n; k++) {
in.nextToken();
d[k] = (int) in.nval;
}
int i = n - 1;
while (i >= 0 && d[i] == 9) d[i--] = 0;
StringBuilder sb = new StringBuilder();
if (i < 0) sb.append("1 ");
else d[i]++;
for (int k = 0; k < n; k++) sb.append(d[k]).append(k + 1 < n ? " " : "");
System.out.println(sb);
}
}