public class Solution { public boolean isAdditiveNumber(String num) { long first = 0;//这是第一个数 long second = 0;//这是第二个数 long third = 0;//这是第三个数 String values = ""; int flag = 0;//标志用于判断最终是不是成功 for (int i = 1; i < num.length() - 1; i++) { String firstString = num.substring(0, i); //因为只要前面有0,第一个数就是0,如果到了其他数可以直接判定为失败 if (i!=1&&firstString.charAt(0) == '0' && firstString.charAt(i-1) != '0') return false; first = Long.valueOf(firstString); for (int j = i + 1; j <= num.length() - 1; j++) { String secondString = num.substring(i, j); if (secondString.charAt(0) == '0'&&secondString.length()!=1) break;//如果当前第一个是0,跳出循环,0就给了上一个数的末尾 second = Long.valueOf(secondString); int k = j; long nowfirst = first; while (j <= num.length()) { values = num.substring(j); third = first + second; String other = String.valueOf(first + second); if (other.charAt(0) == '0'&&other.length()!=1) break; if (other.length() > values.length()) break; if (values.substring(0, other.length()).equals(other)) { j += other.length(); flag = 1;//只要有一次不是,他就会跳出,flag变成0 } else { break; } if (j == num.length() && flag == 1) return true; first = second; second = third; } j = k; first = nowfirst; } flag = 0; } return false; }}