-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSumofDigitsinString.java
More file actions
57 lines (36 loc) · 1.06 KB
/
SumofDigitsinString.java
File metadata and controls
57 lines (36 loc) · 1.06 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.javapractice.stringexamples;
public class SumofDigitsinString {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* Write a java code to find the sum of the given numbers Input:
* "asdf1qwer9as8d7" output: 1+9+8+7 = 25
*/
// Approach-1
String str = "asdf1qwer9as8d7";
str = str.replaceAll("\\D", "");
System.out.println(str);
int intNumber = Integer.parseInt(str);
int sum = 0;
while(intNumber>0)
{
int rem = intNumber%10;
intNumber = intNumber/10;
sum = sum+rem;
}
System.out.println("Sum of numbers = "+sum);
//Approach -2
String st = "asdf1qwer9as8d7";
st = st.replaceAll("[^0-9]", "");
System.out.println("After removing other than numbers is "+st);
int num = Integer.parseInt(st);
int sumof = 0;
while(num>0)
{
int rem = num%10;
num = num/10;
sumof = sumof+rem;
}
System.out.println("Sum of numbers = "+sumof);
}
}