Skip to content

Commit 4a81fa9

Browse files
authored
Update Count Symmetric Integers.java
1 parent f0117cc commit 4a81fa9

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

Easy/Count Symmetric Integers.java

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,27 @@
11
class Solution {
22
public int countSymmetricIntegers(int low, int high) {
3-
int result = 0;
3+
int count = 0;
44
for (int i = low; i <= high; i++) {
5-
String s = String.valueOf(i);
6-
int diff = 0;
7-
int n = s.length();
8-
for (int j = 0; j < n / 2; j++) {
9-
diff += s.charAt(j) - s.charAt(n - j - 1);
10-
}
11-
if (n % 2 == 0 && diff == 0) {
12-
result++;
5+
if (isSymmetric(i)) {
6+
count++;
137
}
148
}
15-
return result;
9+
return count;
10+
}
11+
12+
private static boolean isSymmetric(int num) {
13+
String s = String.valueOf(num);
14+
int n = s.length();
15+
if (n % 2 != 0) {
16+
return false;
17+
}
18+
int sum = 0;
19+
for (int i = 0; i < n / 2; i++) {
20+
sum += Character.getNumericValue(s.charAt(i));
21+
}
22+
for (int i = n / 2; i < n; i++) {
23+
sum -= Character.getNumericValue(s.charAt(i));
24+
}
25+
return sum == 0;
1626
}
1727
}

0 commit comments

Comments
 (0)