-
Notifications
You must be signed in to change notification settings - Fork 19.5k
/
HarshadNumber.java
51 lines (43 loc) · 1.22 KB
/
HarshadNumber.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
46
47
48
49
50
51
package com.thealgorithms.maths;
// Wikipedia for Harshad Number : https://en.wikipedia.org/wiki/Harshad_number
public final class HarshadNumber {
private HarshadNumber() {
}
/**
* A function to check if a number is Harshad number or not
*
* @param n The number to be checked
* @return {@code true} if {@code a} is Harshad number, otherwise
* {@code false}
*/
public static boolean isHarshad(long n) {
if (n <= 0) {
return false;
}
long t = n;
long sumOfDigits = 0;
while (t > 0) {
sumOfDigits += t % 10;
t /= 10;
}
return n % sumOfDigits == 0;
}
/**
* A function to check if a number is Harshad number or not
*
* @param s The number in String to be checked
* @return {@code true} if {@code a} is Harshad number, otherwise
* {@code false}
*/
public static boolean isHarshad(String s) {
final Long n = Long.valueOf(s);
if (n <= 0) {
return false;
}
int sumOfDigits = 0;
for (char ch : s.toCharArray()) {
sumOfDigits += ch - '0';
}
return n % sumOfDigits == 0;
}
}