-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathCountSymmetricIntegers.java
More file actions
33 lines (30 loc) · 989 Bytes
/
CountSymmetricIntegers.java
File metadata and controls
33 lines (30 loc) · 989 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
// https://leetcode.com/problems/count-symmetric-integers
// T: O(N)
// S: O(1)
public class CountSymmetricIntegers {
public int countSymmetricIntegers(int low, int high) {
int count = 0;
for (int start = low ; start <= high ; start++) {
final String number = start + "";
if (isSymmetric(number)) {
count++;
}
}
return count;
}
private static boolean isSymmetric(String number) {
if (number.length() % 2 != 0) {
return false;
}
final String firstHalf = number.substring(0, number.length() / 2);
final String secondHalf = number.substring(number.length() / 2);
return sumOfDigits(firstHalf) == sumOfDigits(secondHalf);
}
private static int sumOfDigits(final String number) {
int sum = 0;
for (int i = 0 ; i < number.length() ; i++) {
sum += number.charAt(i) - '0';
}
return sum;
}
}