Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 472bc9a

Browse files
authored
Add files via upload
1 parent ea08a8c commit 472bc9a

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

‎FindSumOfNumbersApproachRegex.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package powerJavaLearning;
2+
3+
public class FindSumOfNumbersApproachRegex {
4+
/*Write a java code to find the sum of the given numbers
5+
Input: "asdf1qwer9as8d7"
6+
output: 1+9+8+7 = 25 */
7+
public static void main(String[] args) {
8+
String input ="asdf1qwer9as8d7";
9+
10+
//using charArray operation
11+
System.out.println("logic using characterArray operation");
12+
String numberFromString = input.replaceAll("\\D", "");
13+
int sumAp1=0;
14+
char[] charArray = numberFromString.toCharArray();
15+
for (int i = 0; i < numberFromString.length(); i++) {
16+
char charAt = charArray[i];
17+
sumAp1 += Integer.parseInt(String.valueOf(charAt));
18+
}
19+
System.out.println("Sum of Integers "+sumAp1);
20+
21+
22+
//using mathematical operation
23+
System.out.println("logic using mathematical operation");
24+
int number=Integer.parseInt(input.replaceAll("[^0-9]", ""));
25+
int sumAp2=0;
26+
while (number>0) {
27+
sumAp2=sumAp2+number%10;
28+
number=number/10;
29+
}
30+
31+
System.out.println("Sum of Integers "+sumAp2);
32+
}
33+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /