koenjazh-CNfresde
짬뽕얼큰하게의 맨땅에 헤딩 :: Count Symmetric Integers

Leetcode Problem:

Summary

  • The problem is to find the number of symmetric integers in the given range [low, high].

Approach

  • The solution checks for symmetry by comparing the sum of the first n digits with the sum of the last n digits for each integer in the range
  • It also handles numbers with an odd number of digits by not including them in the count.

Complexity

  • O(n) where n is the number of integers in the range, as it checks each integer once.

Explanation

  • The solution iterates over each integer in the range and checks for symmetry
  • For numbers with an even number of digits (4 or more), it calculates the sum of the first n digits and the sum of the last n digits
  • If they are equal, it increments the count
  • For numbers with 3 digits, it directly compares the two middle digits
  • The time complexity is linear as it checks each integer once.

Solution Code:


class Solution {
public:
    int countSymmetricIntegers(int low, int high) {
        int ans = 0;
        for(int i = low; i <= high; i++){
            if(i / 1000){
                int a = i / 1000;
                int b = (i % 1000) / 100;
                int c = (i % 100) / 10;
                int d = (i % 10);
                if((a + b) == (c + d)){
                    ans++;
                }
            } else if( ((i/10) > 0) && ((i/10) < 10)){
                int a = i/10;
                int b = i%10;
                if(a == b) ans++;
            }
        }
        return ans;
    }
};
블로그 이미지

짬뽕얼큰하게

,