forked from mirandaio/codingbat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsumNumbers.java
More file actions
35 lines (29 loc) · 1.12 KB
/
sumNumbers.java
File metadata and controls
35 lines (29 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* Given a string, return the sum of the numbers appearing in the string,
* ignoring all other characters. A number is a series of 1 or more digit
* chars in a row.
*/
public int sumNumbers(String str) {
int sum = 0;
int i = 0;
int begin;
int end;
while(i < str.length() && !Character.isDigit(str.charAt(i)))
i++;
begin = i;
end = i;
while(i < str.length()) {
if(!Character.isDigit(str.charAt(i))) {
sum += Integer.parseInt(str.substring(begin, end));
while(i < str.length() && !Character.isDigit(str.charAt(i)))
i++;
begin = i;
end = i;
} else {
end++;
i++;
}
}
if(end > begin)
sum += Integer.parseInt(str.substring(begin, end));
return sum;
}