Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

java - How to calculate sum of all numbers in a string

How do I calculate the sum of all the numbers in a string? In the example below, the expected result would be 4+8+9+6+3+5. My attempt is below. Also could I calculate the sum of only those numbers which are divisible by 2?

int sum=0;
String s = "jklmn489pjro635ops";
for(int i=0; i<s.length(); i++) {
    char temp = s.charAt(i);
    if (Character.isDigit(temp)) {
        int b = Integer.parseInt(String.valueOf(temp));
        sum=sum+b;
    }
}
System.out.println(sum);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Parsing chars back to String and then to Integer is too expensive, since you already have a char. You should try doing this:

 String a = "jklmn489pjro635ops";
 int sum = 0;
 int evenSum = 0;
 for (char c : a.replaceAll("\D", "").toCharArray()) {
     int digit = c - '0';
     sum += digit;
     if (digit % 2 == 0) {
         evenSum += digit;
     }
 }
 System.out.println(sum);
 System.out.println(evenSum);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...