LeetCode906. Super Palindromes

文章目录

    • 一、题目
    • 二、题解

一、题目

Let’s say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome.

Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right].

Example 1:

Input: left = “4”, right = “1000”
Output: 4
Explanation: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.
Example 2:

Input: left = “1”, right = “2”
Output: 1

Constraints:

1 <= left.length, right.length <= 18
left and right consist of only digits.
left and right cannot have leading zeros.
left and right represent integers in the range [1, 1018 - 1].
left is less than or equal to right.

二、题解

class Solution {
public:
    bool isPalindrome(long long num){
        long offset = 1;
        while(num / offset >= 10){
            offset *= 10;
        }
        while(num){
            if(num / offset != num % 10) return false;
            num = (num % offset) / 10;
            offset /= 100;
        }
        return true;
    }
    long long oddEnlarge(long long seed){
        long long res = seed;
        seed /= 10;
        while(seed){
            res = res * 10 + seed % 10;
            seed /= 10;
        }
        return res;
    }
    long long evenEnlarge(long long seed){
        long long res = seed;
        while(seed){
            res = res * 10 + seed % 10;
            seed /= 10;
        }
        return res;
    }
    bool check(long long num,long l,long r){
        return num >= l && num <= r && isPalindrome(num);
    }
    int superpalindromesInRange(string left, string right) {
        long long l = stol(left);
        long long r = stol(right);
        long long limit = (long long)sqrt((double)r);
        long long seed = 1;
        long long num = 0;
        int res = 0;
        do{
            //偶数长度回文数
            num = evenEnlarge(seed);
            if(num <= (long long)sqrt(double(LONG_LONG_MAX)) && check(num * num,l,r)) res++;
            //奇数长度回文数
            num = oddEnlarge(seed);
            if(num <= (long long)sqrt(double(LONG_LONG_MAX)) && check(num * num,l,r)) res++;
            seed++;
        }while(num < limit);
        return res;
    }
};

你可能感兴趣的:(算法,数据结构,c++,leetcode)