Skip to content

2843. Count Symmetric Integers 👍

  • Time: $O(\texttt{high})$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int countSymmetricIntegers(int low, int high) {
    int ans = 0;

    for (int num = low; num <= high; ++num)
      if (isSymmetricInteger(num))
        ++ans;

    return ans;
  }

 private:
  bool isSymmetricInteger(int num) {
    if (num >= 10 && num <= 99)
      return num / 10 == num % 10;
    if (num >= 1000 && num <= 9999) {
      const int left = num / 100;
      const int right = num % 100;
      return left / 10 + left % 10 == right / 10 + right % 10;
    }
    return false;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int countSymmetricIntegers(int low, int high) {
    int ans = 0;

    for (int num = low; num <= high; ++num)
      if (isSymmetricInteger(num))
        ++ans;

    return ans;
  }

  private boolean isSymmetricInteger(int num) {
    if (num >= 10 && num <= 99)
      return num / 10 == num % 10;
    if (num >= 1000 && num <= 9999) {
      final int left = num / 100;
      final int right = num % 100;
      return left / 10 + left % 10 == right / 10 + right % 10;
    }
    return false;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def countSymmetricIntegers(self, low: int, high: int) -> int:
    def isSymmetricInteger(num: int) -> bool:
      if num >= 10 and num <= 99:
        return num // 10 == num % 10
      if num >= 1000 and num <= 9999:
        left = num // 100
        right = num % 100
        return left // 10 + left % 10 == right // 10 + right % 10
      return False

    return sum(isSymmetricInteger(num) for num in range(low, high + 1))