File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments