问题背景
给你两个正整数 l o w low low 和 h i g h high high。
对于一个由 2 × n 2 \times n 2×n 位数字组成的整数 x x x,如果其前 n n n 位数字之和与后 n n n 位数字之和相等,则认为这个数字是一个对称整数。
返回在 [ l o w , h i g h ] [low, high] [low,high] 范围内的 对称整数的数目 。
数据约束
- 1 ≤ l o w ≤ h i g h ≤ 1 0 4 1 \le low \le high \le 10 ^ 4 1≤low≤high≤104
解题过程
数据范围不大,直接按要求模拟就可以解决。
具体实现
class Solution {public int countSymmetricIntegers(int low, int high) {int res = 0;for (int i = low; i <= high; i++) {char[] s = Integer.toString(i).toCharArray();int n = s.length;if (n % 2 == 1) {continue;}int diff = 0;for (int j = 0; j < n / 2; j++) {diff += s[j];}for (int j = n / 2; j < n; j++) {diff -= s[j];}if (diff == 0) {res++;}}return res;}
}