LeetCode 2843: Count Symmetric Integers Solution

Master LeetCode problem 2843 ( Count Symmetric Integers), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2843. Count Symmetric Integers

Problem Explanation

Explanation:

To solve this problem, we can iterate through the range [low, high] and for each number, check if it is symmetric based on the given conditions. We can determine if a number is symmetric by comparing the sums of its first half and second half digits. If the number has an odd number of digits, it is not symmetric. If the sums of the first half and second half digits are equal, the number is symmetric.

  1. Iterate through the range [low, high].
  2. For each number, check if it has an even number of digits.
  3. If the number has an even number of digits, calculate the sums of the first half and second half digits.
  4. If the sums are equal, increment the count of symmetric integers.
  5. Return the count of symmetric integers.

Time Complexity: O(N * M), where N is the number of integers in the range [low, high] and M is the number of digits in each integer.

Space Complexity: O(1).

:

Solution Code

class Solution {
    public int countSymmetricIntegers(int low, int high) {
        int count = 0;
        
        for (int num = low; num <= high; num++) {
            if (isSymmetric(num)) {
                count++;
            }
        }
        
        return count;
    }
    
    private boolean isSymmetric(int num) {
        String str = String.valueOf(num);
        if (str.length() % 2 != 0) {
            return false;
        }
        
        int half = str.length() / 2;
        int sum1 = 0, sum2 = 0;
        
        for (int i = 0; i < half; i++) {
            sum1 += str.charAt(i) - '0';
            sum2 += str.charAt(i + half) - '0';
        }
        
        return sum1 == sum2;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2843 ( Count Symmetric Integers)?

This page provides optimized solutions for LeetCode problem 2843 ( Count Symmetric Integers) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2843 ( Count Symmetric Integers)?

The time complexity for LeetCode 2843 ( Count Symmetric Integers) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2843 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2843 in Java, C++, or Python.

Back to LeetCode Solutions