Java – sum of substrings of numbers
•
Java
What is the best solution to find the sum of digital substrings?
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: // O(n) sum += startwith(i) // O(n) return sum
What's the best plan? What is the best way?
This 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; }
Solution
Observation:
>For the number XY, you have 11x 2Y. > For the number XYZ, you have 111x 22y 3Z. > For wxyz, you have 1111w 222x 33y 4Z
This is my c# implementation, although porting to Java should be trivial:
static long SumSubtring(String s) { long sum = 0,mult = 1; for (int i = s.Length; i > 0; i--,mult = mult * 10 + 1) sum += (s[i - 1] - '0') * mult * i; return sum; }
Notice that it is actually o (n)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码