An additive number is a string whose digits can form an additive sequence. A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.
Given a string containing only digits, return true
if it is an additive number or false
otherwise.
Example 1:
Input: "112358"
Output: true
Explanation: The digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
Example 2:
Input: "199100199"
Output: true
Explanation: The additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
Constraints:
0
?
0
, it should be exactly 0
because we don’t want leading zeroes in any part of the sequence.0
.Here’s the implementation of the described strategy:
public class Solution {
public boolean isAdditiveNumber(String num) {
int n = num.length();
for (int i = 1; i <= n / 2; i++) {
if (num.charAt(0) == '0' && i > 1) return false; // Leading zero case
Long num1 = Long.parseLong(num.substring(0, i));
for (int j = i + 1; n - j >= j - i && n - j >= i; j++) {
if (num.charAt(i) == '0' && j - i > 1) break; // Leading zero case
Long num2 = Long.parseLong(num.substring(i, j));
if (isValid(num, num1, num2, j)) return true;
}
}
return false;
}
private boolean isValid(String num, Long num1, Long num2, int start) {
int n = num.length();
while (start < n) {
num2 = num2 + num1;
num1 = num2 - num1;
String sumStr = num2.toString();
if (!num.startsWith(sumStr, start)) return false;
start += sumStr.length();
}
return true;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.isAdditiveNumber("112358")); // true
System.out.println(solution.isAdditiveNumber("199100199")); // true
System.out.println(solution.isAdditiveNumber("123")); // true
System.out.println(solution.isAdditiveNumber("1023")); // false
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?