Skip to content

Commit b4839c2

Browse files
Added SumOfDigits
1 parent 98a191c commit b4839c2

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

Maths/SumOfDigits.java

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package Maths;
2+
3+
public class SumOfDigits {
4+
public static void main(String[] args) {
5+
assert
6+
sumOfDigits(-123) == 6
7+
&& sumOfDigitsRecursion(-123) == 6
8+
&& sumOfDigitsFast(-123) == 6;
9+
10+
assert sumOfDigits(0) == 0
11+
&& sumOfDigitsRecursion(0) == 0
12+
&& sumOfDigitsFast(0) == 0;
13+
14+
15+
assert sumOfDigits(12345) == 15
16+
&& sumOfDigitsRecursion(12345) == 15
17+
&& sumOfDigitsFast(12345) == 15;
18+
}
19+
20+
/**
21+
* Calculate the sum of digits of a number
22+
*
23+
* @param number the number contains digits
24+
* @return sum of digits of given {@code number}
25+
*/
26+
public static int sumOfDigits(int number) {
27+
number = number < 0 ? -number : number; /* calculate abs value */
28+
int sum = 0;
29+
while (number != 0) {
30+
sum += number % 10;
31+
number /= 10;
32+
}
33+
return sum;
34+
}
35+
36+
/**
37+
* Calculate the sum of digits of a number using recursion
38+
*
39+
* @param number the number contains digits
40+
* @return sum of digits of given {@code number}
41+
*/
42+
public static int sumOfDigitsRecursion(int number) {
43+
number = number < 0 ? -number : number; /* calculate abs value */
44+
return number < 10 ? number : number % 10 + sumOfDigitsRecursion(number / 10);
45+
}
46+
47+
/**
48+
* Calculate the sum of digits of a number using char array
49+
*
50+
* @param number the number contains digits
51+
* @return sum of digits of given {@code number}
52+
*/
53+
public static int sumOfDigitsFast(int number) {
54+
number = number < 0 ? -number : number; /* calculate abs value */
55+
char[] digits = (number + "").toCharArray();
56+
int sum = 0;
57+
for (int i = 0; i < digits.length; ++i) {
58+
sum += digits[i] - '0';
59+
}
60+
return sum;
61+
}
62+
}

0 commit comments

Comments
 (0)