-
Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathSumOfDigits.java
45 lines (41 loc) · 1.27 KB
/
SumOfDigits.java
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
package com.thealgorithms.maths;
public final class SumOfDigits {
private SumOfDigits() {
}
/**
* Calculate the sum of digits of a number
*
* @param number the number contains digits
* @return sum of digits of given {@code number}
*/
public static int sumOfDigits(int number) {
final int base = 10;
number = Math.abs(number);
int sum = 0;
while (number != 0) {
sum += number % base;
number /= base;
}
return sum;
}
/**
* Calculate the sum of digits of a number using recursion
*
* @param number the number contains digits
* @return sum of digits of given {@code number}
*/
public static int sumOfDigitsRecursion(int number) {
final int base = 10;
number = Math.abs(number);
return number < base ? number : number % base + sumOfDigitsRecursion(number / base);
}
/**
* Calculate the sum of digits of a number using char array
*
* @param number the number contains digits
* @return sum of digits of given {@code number}
*/
public static int sumOfDigitsFast(final int number) {
return String.valueOf(Math.abs(number)).chars().map(c -> c - '0').reduce(0, Integer::sum);
}
}