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;
}
};
'알고리즘' 카테고리의 다른 글
Count Good Numbers (0) | 2025.04.13 |
---|---|
Find the Count of Good Integers (1) | 2025.04.12 |
Count the Number of Powerful Integers (0) | 2025.04.11 |
Minimum Operations to Make Array Values Equal to K (0) | 2025.04.10 |
Minimum Number of Operations to Make Elements in Array Distinct (0) | 2025.04.08 |