|
| 1 | +package com.stevesun.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * Additive number is a string whose digits can form additive sequence. |
| 5 | +
|
| 6 | + 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. |
| 7 | +
|
| 8 | + For example: |
| 9 | + "112358" is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8. |
| 10 | +
|
| 11 | + 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8 |
| 12 | + "199100199" is also an additive number, the additive sequence is: 1, 99, 100, 199. |
| 13 | + 1 + 99 = 100, 99 + 100 = 199 |
| 14 | + Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid. |
| 15 | +
|
| 16 | + Given a string containing only digits '0'-'9', write a function to determine if it's an additive number. |
| 17 | +
|
| 18 | + Follow up: |
| 19 | + How would you handle overflow for very large input integers? |
| 20 | + */ |
| 21 | +public class AdditiveNumber { |
| 22 | + |
| 23 | + public boolean isAdditiveNumber(String num) { |
| 24 | + if (num == null || num.length() < 3) { |
| 25 | + return false; |
| 26 | + } |
| 27 | + int len = num.length(); |
| 28 | + for (int i = 1; i < len; i++) { |
| 29 | + for (int j = i + 1; j < len; j++) { |
| 30 | + int first = 0, second = i, third = j; |
| 31 | + if (num.charAt(second) == '0' && third > second + 1){ |
| 32 | + break;// This is the pruning part, for each iteration, if this condition |
| 33 | + // meets, returns false immediately |
| 34 | + } |
| 35 | + while (third < len) { |
| 36 | + Long result = Long.parseLong(num.substring(first, second)) |
| 37 | + + Long.parseLong(num.substring(second, third)); |
| 38 | + if (num.substring(third).startsWith((result.toString()))) { |
| 39 | + first = second; |
| 40 | + second = third; |
| 41 | + third += result.toString().length(); |
| 42 | + } else { |
| 43 | + break;// This is another part of pruning! Cool! |
| 44 | + } |
| 45 | + } |
| 46 | + if(third == len){ |
| 47 | + return true; |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + return false; |
| 52 | + } |
| 53 | + |
| 54 | +} |
0 commit comments