Skip to content

Commit a645e7c

Browse files
solves #3099: Harshad Number in java
1 parent 80f303b commit a645e7c

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -901,7 +901,7 @@
901901
| 3083 | [Existence of a Substring in a String and Its Reverse](https://leetcode.com/problems/existence-of-a-substring-in-a-string-and-its-reverse) | [![Java](assets/java.png)](src/ExistenceOfASubstringInAStringAndItsReverse.java) | |
902902
| 3090 | [Maximum Length Substring With Two Occurrences](https://leetcode.com/problems/maximum-length-substring-with-two-occurrences) | [![Java](assets/java.png)](src/MaximumLengthSubstringWithTwoOccurrences.java) | |
903903
| 3095 | [Shortest Subarray With OR at Least K I](https://leetcode.com/problems/shortest-subarray-with-or-at-least-k-i) | [![Java](assets/java.png)](src/ShortestSubarrayWithORAtLeastKI.java) | |
904-
| 3099 | [Harshad Number](https://leetcode.com/problems/harshad-number) | | |
904+
| 3099 | [Harshad Number](https://leetcode.com/problems/harshad-number) | [![Java](assets/java.png)](src/HarshadNumber.java) | |
905905
| 3105 | [Longest Strictly Increasing or Strictly Decreasing Subarray](https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray) | | |
906906
| 3110 | [Score of a String](https://leetcode.com/problems/score-of-a-string) | | |
907907
| 3114 | [Latest Time You Can Obtain After Replacing Characters](https://leetcode.com/problems/latest-time-you-can-obtain-after-replacing-characters) | | |

Diff for: src/HarshadNumber.java

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// https://leetcode.com/problems/harshad-number
2+
// T: O(log(N))
3+
// S: O(1)
4+
5+
public class HarshadNumber {
6+
public int sumOfTheDigitsOfHarshadNumber(int x) {
7+
final int sumOfDigits = sumOfDigits(x);
8+
if (x % sumOfDigits == 0) {
9+
return sumOfDigits;
10+
}
11+
return -1;
12+
}
13+
14+
private static int sumOfDigits(int x) {
15+
int sum = 0;
16+
while (x > 0) {
17+
sum += x % 10;
18+
x /= 10;
19+
}
20+
return sum;
21+
}
22+
}

0 commit comments

Comments
 (0)