What is the best solution to find the sum of the substring of a number?
For example, Sum (123) = 1 + 2 + 3 + 12 + 23 + 123 = 164.
I think this is O (n ^ 2). because
sum = 0
for i in number:
sum += startwith(i)
return sum
Any optimal solution? What is the best approach?
Here is my solution, but O (n ^ 2):
public static int sumOfSubstring(int i) {
int sum = 0;
String s = Integer.toString(i);
for (int j = 0, bound = s.length(); j < bound; j++) {
for (int k = j; k < bound; k++) {
String subString = s.subSequence(j, k + 1).toString();
sum += Integer.valueOf(subString);
}
}
return sum;
}
user467871
source
share