BiruLyu
6/20/2017 - 7:33 AM

``````public class Solution {
if (num == null || num.length() < 3) return false;
int len = num.length();
for (int i = 1; i <= len / 2; i++) {
for (int j = 1; j <= (len - i) / 2; j++) {
if (num.charAt(0) == '0' && i > 1) break;
if (num.charAt(i) == '0' && j > 1) break;
if(helper(num, i, j)) return true;
}
}
return false;
}

private boolean helper(String num, int i, int j) {
String sum;
Long num1 = Long.parseLong(num.substring(0, i));
Long num2 = Long.parseLong(num.substring(i, i + j));
for (int start = i + j; start < num.length(); start += sum.length()) {
num2 += num1;
num1 = num2 - num1;
sum = num2.toString();
if(!num.startsWith(sum, start)) {
return false;
}
}
return true;
}
}``````
``````
public class Solution {
int n = num.length();
for (int i = 1; i <= n / 2; ++i) {
if (num.charAt(0) == '0' && i > 1) return false;
BigInteger x1 = new BigInteger(num.substring(0, i));
for (int j = 1; Math.max(j, i) <= n - i - j; ++j) {
if (num.charAt(i) == '0' && j > 1) break;
BigInteger x2 = new BigInteger(num.substring(i, i + j));
if (isValid(x1, x2, j + i, num)) return true;
}
}
return false;
}
private boolean isValid(BigInteger x1, BigInteger x2, int start, String num) {
if (start == num.length()) return true;