Leetcode 2843. Count Symmetric Integers
You are given two integers, low and high. A symmetric integer is an integer that reads the same both forward and backward (i.e., a palindrome). Your task is to count the number of symmetric integers between low and high, inclusive.
For example, if low is 10 and high is 150, there are several symmetric integers such as 11, 22, etc., up to 121.
low and high?low and high guaranteed to be non-negative and non-zero?low is equal to high?low to high.low to high.N is the number of integers between low and high, and k is the average number of digits in the integers. Converting a number to a string and checking if it is a palindrome both take O(k) time.#include <iostream>
#include <string>
class Solution {
public:
int countSymmetricIntegers(int low, int high) {
int count = 0;
for (int i = low; i <= high; ++i) {
if (isSymmetric(i)) {
count++;
}
}
return count;
}
private:
bool isSymmetric(int num) {
std::string s = std::to_string(num);
int left = 0;
int right = s.size() - 1;
while (left < right) {
if (s[left] != s[right]) {
return false;
}
left++;
right--;
}
return true;
}
};
int main() {
Solution sol;
int low = 10;
int high = 150;
std::cout << "Number of symmetric integers: " << sol.countSymmetricIntegers(low, high) << std::endl;
return 0;
}
Solution with two member functions.low to high and uses the isSymmetric helper method to check if a number is a palindrome. It keeps a count of symmetric integers.Solution class and call the countSymmetricIntegers method with the sample low and high values, then print the result.This solution ensures all numbers in the given range are checked, and only the symmetric ones are counted.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?