forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSumOfDigits.java
More file actions
46 lines (42 loc) · 971 Bytes
/
SumOfDigits.java
File metadata and controls
46 lines (42 loc) · 971 Bytes
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
package com.examplehub.maths;
public class SumOfDigits {
/**
* Sum of digits.
*
* @param number the number.
* @return the sum of digits.
*/
public static int sumOfDigits(long number) {
number = Math.abs(number);
int sum = 0;
while (number != 0) {
sum = (int) (sum + number % 10);
number /= 10;
}
return sum;
}
/**
* Sum of digits using byte array.
*
* @param number the number.
* @return the sum of digits.
*/
public static int sumOfDigitsSecond(int number) {
byte[] bytes = (Math.abs(number) + "").getBytes();
int sum = 0;
for (byte temp : bytes) {
sum += temp - '0';
}
return sum;
}
/**
* Sum of digits using recursion.
*
* @param number the number.
* @return the sum of digits.
*/
public static int sumOfDigitsRecursion(int number) {
number = Math.abs(number);
return number < 10 ? number : number % 10 + sumOfDigits(number / 10);
}
}