Plus One on a Digit Array
Problem
An array holds the digits of a whole number, the biggest digit first (for example 1 2 9 means 129). Add one to the number and print the digits of the result, separated by spaces. The number has no leading zero, except the number 0 itself.
Constraints
- 1 <= n <= 100
- 0 <= a[i] <= 9
Examples
Input
3 1 2 9
Output
1 3 0
Solutions
We add one at the last digit. A 9 turns into 0 and passes the carry to the left. We stop at the first digit that is not 9. Only when all digits are 9 does the array become longer.
/*
* Problem : Plus one.
* Input : n, then the digits.
* Output : The new digits.
* Approach: Carry from the right.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int[] solve(int[] a) {
// Step 1: Start at the last digit and add the carry. Work on a copy.
int[] digits = a.clone();
for (int i = digits.length - 1; i >= 0; i--) {
// Step 2: A digit below 9 takes the one, and we are done.
if (digits[i] < 9) {
digits[i]++;
return digits;
}
// Step 3: A 9 becomes 0 and the carry goes to the next digit on the left.
digits[i] = 0;
}
// Step 4: All digits were 9. The result is 1 followed by zeros.
int[] result = new int[digits.length + 1];
result[0] = 1;
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(Arrays.stream(solve(a)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
}
}
Hints (2)
- What happens to a 9?
- When does the length grow?